我使用RSA加密來編碼/解碼信息 加密工作正常,但解密時遇到此錯誤。解密數據時出錯
rsa.Decrypt(dataByte, false);
描述:在當前web請求的執行過程中發生了未處理的異常。請查看堆棧跟蹤以獲取有關該錯誤的更多信息以及源代碼的位置。
異常詳細信息:System.Security.Cryptography.CryptographicException:參數不正確。
代碼:
string en= x509_Encrypt(Current_Record_Hmac, PFXFile, s_pass);
string de= ByteToString(X509_Decrypt(en, PFXFile, s_pass));
public static byte[] X509_Decrypt(string data, string certificateFile, string password)
{
var dataArray = data.Split(new char[] { ',' });
byte[] dataByte = new byte[dataArray.Length];
for (int i = 0; i < dataArray.Length; i++)
{
dataByte[i] = Convert.ToByte(dataArray[i]);
}
X509Certificate2 cert = new X509Certificate2(certificateFile, password);
var rsa = new RSACryptoServiceProvider();
var x509_privateKey = cert.PrivateKey;
string pri = x509_privateKey.ToString();
string x509_privateKey_ToString = x509_privateKey.ToString();
string X509_publicKey = ByteToString(cert.GetPublicKey());
x509_privateKey_ToString = rsa.ToXmlString(true);
X509_publicKey = rsa.ToXmlString(false);
rsa.FromXmlString(x509_privateKey_ToString);
var decryptedByte = rsa.Decrypt(dataByte, false);
return (decryptedByte);
}
public string x509_Encrypt(string input, string certificateFile, string password)
{
var dataToEncrypt = _encoder.GetBytes(input);
var encoding = new System.Text.ASCIIEncoding();
X509Certificate2 cert = new X509Certificate2(certificateFile, password);
var x509_privateKey = cert.PrivateKey;
string x509_privateKey_ToString = ByteToString(encoding.GetBytes(x509_privateKey.ToString()));
string X509_publicKey = ByteToString(cert.GetPublicKey());
//Encrypting the text using the public key
RSACryptoServiceProvider cipher = new RSACryptoServiceProvider();
x509_privateKey_ToString = cipher.ToXmlString(true);
X509_publicKey = cipher.ToXmlString(false);
cipher.FromXmlString(X509_publicKey);
var encryptedByteArray = cipher.Encrypt(dataToEncrypt, false).ToArray();
var length = encryptedByteArray.Count();
var item = 0;
var sb = new StringBuilder();
foreach (var x in encryptedByteArray)
{
item++;
sb.Append(x);
if (item < length)
sb.Append(",");
}
return sb.ToString();
}