System.Security.Cryptography.CryptographicException: 'Key not valid for use in specified state.
public class RsaEncryptionService
{
private static RSACryptoServiceProvider csp = new RSACryptoServiceProvider(2048);
private RSAParameters _privateKey;
private RSAParameters _publicKey;
public RsaEncryptionService()
{
_privateKey = csp.ExportParameters(true);
_publicKey = csp.ExportParameters(false);
}
public string GetPublicKey()
{
var sw = new StringWriter();
var xmlSerializer = new XmlSerializer(typeof(RSAParameters));
xmlSerializer.Serialize(sw, _publicKey);
return sw.ToString();
}
public string GetPrivateKey()
{
var sw = new StringWriter();
var xmlSerializer = new XmlSerializer(typeof(RSAParameters));
xmlSerializer.Serialize(sw, _privateKey);
return sw.ToString();
}
public string Encript(string plainText)
{
csp = new RSACryptoServiceProvider();
csp.ImportParameters(_publicKey);
var dataBytes = Encoding.Unicode.GetBytes(plainText);
var cypherData = csp.Encrypt(dataBytes, false);
return Convert.ToBase64String(cypherData);
}
public string Decript(string cypherText)
{
var dataBytes = Convert.FromBase64String(cypherText);
csp.ImportParameters(_privateKey);
var plaintextBytes = csp.Decrypt(dataBytes, false);
return Encoding.Unicode.GetString(plaintextBytes);
}
}
Encript
方法一样,您需要在
csp
方法的开头将
RSACryptoServiceProvider
分配给新的
Decript
。
RSACryptoServiceProvider 构造函数的 Microsoft 文档有一个实际操作的示例:
public static byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
{
try
{
byte[] decryptedData;
//Create a new instance of RSACryptoServiceProvider.
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
//Import the RSA Key information. This needs
//to include the private key information.
RSA.ImportParameters(RSAKeyInfo);
//Decrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
decryptedData = RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
}
return decryptedData;
}
//Catch and display a CryptographicException
//to the console.
catch (CryptographicException e)
{
Console.WriteLine(e.ToString());
return null;
}
}