Bob和Alice非对称加解密实现

问题描述

我正在尝试使用 RSACryptoServiceProvider

构建 Bob 和 Alice 的非对称加密和解密实现

因为我有

  1. 控制台应用 Bob(可以视为发件人)
  2. 控制台应用 Alice(可以视为接收者)

控制台应用程序 Bob 可以使用其公钥进行加密,然后控制台应用程序 Alice 可以使用其私钥对其进行解密

所以这是Bob Console 应用

    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 Console 应用

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: '参数是 不正确。

您能否就此提出建议:)

解决方法

这里的原因是您要在两个应用程序中构建一个公钥/私钥对。

本质上,您是在尝试使用 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
参数不正确。