我正在尝试使用RSACryptoServiceProvider构建Bob和Alice非对称加密和解密实现
为此,我有
控制台应用Bob可以使用其公钥进行加密,然后控制台应用Alice可以使用其私钥对其进行解密。
这是Bob控制台应用程序
class Program
{
static void Main(string[] args)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
string publicKey = rsa.ToXmlString(false);
string privateKey = rsa.ToXmlString(true);
EncryptText(publicKey, "Hello from C# Corner", "encryptedData.dat");
}
public static void EncryptText(string publicKey, string text, string fileName)
{
UnicodeEncoding byteConverter = new UnicodeEncoding();
byte[] dataToEncrypt = byteConverter.GetBytes(text);
byte[] encryptedData;
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(publicKey);
encryptedData = rsa.Encrypt(dataToEncrypt, false);
}
File.WriteAllBytes(fileName, encryptedData);
Console.WriteLine("Data has been encrypted");
}
}这是Alice控制台应用程序
class Program
{
static void Main(string[] args)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
string publicKey = rsa.ToXmlString(false);
string privateKey = rsa.ToXmlString(true);
Console.WriteLine("Decrypted message: {0}", DecryptData(privateKey, "encryptedData.dat"));
}
public static string DecryptData(string privateKey, string fileName)
{
byte[] dataToDecrypt = File.ReadAllBytes(fileName);
byte[] decryptedData;
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(privateKey);
decryptedData = rsa.Decrypt(dataToDecrypt, false);
}
UnicodeEncoding byteConverter = new UnicodeEncoding();
return byteConverter.GetString(decryptedData);
}
}当它解密时,我得到的错误是
System.Security.Cryptography.CryptographicException:‘参数不正确。
(请你就此提出意见:)
发布于 2021-06-11 12:48:43
这里的原因是,您正在两个应用程序中构造一个公钥/私钥对。
本质上,你试图用Bob的公钥加密一些东西,并试图用Alice的私钥解密它。这不管用。
您需要构造1对,然后使用来自该对的公钥进行加密,使用来自同一对的私钥进行解密。
这样做是可行的:
void Main()
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
string publicKey = rsa.ToXmlString(false);
string privateKey = rsa.ToXmlString(true);
EncryptText(publicKey, "Test", @"d:\temp\test.dat");
Console.WriteLine(DecryptData(privateKey, @"d:\temp\test.dat"));
}但是,如果在调用解密之前创建了一个新的对,则会得到以下错误:
WindowsCryptographicException 参数不正确。
https://stackoverflow.com/questions/67937201
复制相似问题