问题描述
首先,我仅出于学术目的编写以下代码.我之所以这么说是因为我没有把它放在生产环境中,因此我绕过"了一些我需要做的开销,我只需要能够使用加密/解密字符串下面的代码.有几次我能够做到这一点,但由于某种原因,我开始收到CryptographicException Bad Data"并且不确定是什么导致了问题.
First, I have only written the code below for academic purposes. The reason I say this is because I am not putting this in a production environment, and therefor am "bypassing" some of the overhead that I would need to do if I was, I simply need to be able to encrypt/decrypt a string using the code below. I was able to do it a few time, but for some reason, I started receiving "CryptographicException Bad Data" and am not sure what might be causing the problem.
private string RSAEncrypt(string value)
{
byte[] encryptedData = Encoding.Unicode.GetBytes(value);
CspParameters cspParams = new CspParameters();
cspParams.KeyContainerName = _rsaContainerName;
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(2048,cspParams))
{
encryptedData = RSA.Encrypt(encryptedData, false);
return Convert.ToBase64String(encryptedData);
}
}
private string RSADecrypt(string value)
{
byte[] encryptedData = Encoding.Unicode.GetBytes(value);
CspParameters cspParams = new CspParameters();
cspParams.KeyContainerName = _rsaContainerName;
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(2048,cspParams))
{
encryptedData = RSA.Decrypt(encryptedData,false);
return Convert.ToBase64String(encryptedData);
}
}
它只是在 RSADecrypt 调用上抛出这个异常.
It is only throwing this exception on the RSADecrypt call.
有什么想法吗?我在某处读到它可能与传递给 RSA.Decrypt 的 encryptedData 的预期大小有关.
Any ideas? I read somewhere it might have to do with the expected size of encryptedData that is passed into RSA.Decrypt.
谢谢}
推荐答案
使用字符串编码(即
Encoding.Unicode
)来回转换明文.使用 Base-64 来回转换加密数据(即
Convert.[To/From]Base64String
);Convert the encrypted data back and forth using Base-64 (i.e.
Convert.[To/From]Base64String
);像这样:
private string RSAEncrypt(string value) { byte[] plaintext = Encoding.Unicode.GetBytes(value); CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = _rsaContainerName; using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(2048,cspParams)) { byte[] encryptedData = RSA.Encrypt(plaintext, false); return Convert.ToBase64String(encryptedData); } } private string RSADecrypt(string value) { byte[] encryptedData = Convert.FromBase64String(value); CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = _rsaContainerName; using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(2048,cspParams)) { byte[] decryptedData = RSA.Decrypt(encryptedData,false); return Encoding.Unicode.GetString(decryptedData); } }
这篇关于“坏数据"加密异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!