問題描述
首先,我僅出于學術目的編寫以下代碼.我之所以這么說是因為我沒有把它放在生產環境中,因此我繞過"了一些我需要做的開銷,我只需要能夠使用加密/解密字符串下面的代碼.有幾次我能夠做到這一點,但由于某種原因,我開始收到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); } }
這篇關于“壞數據"加密異常的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!