RSA - System.Security.Cryptography.CryptographicException:“密钥在指定状态下使用无效”

问题描述 投票:0回答:1
我正在为我的大学在 Visual Studio 中制作一个 C# 项目。我在 RSA 加密方面遇到问题。当尝试解密字符串时,我收到错误

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); } }
    
c# encryption rsa
1个回答
0
投票
与您的

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; } }
    
© www.soinside.com 2019 - 2024. All rights reserved.