RSACryptoServiceProvider 使用自己的 public 和私钥加密和解密

RSACryptoServiceProvider encrypt and decrypt using own public and private key

有人告诉我,对于非对称加密,您可以使用 public 密钥加密明文,然后使用您的私钥对其进行解密。所以我尝试了以下方法:

    static void Main(string[] args)
    {
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        string pubkey = rsa.ToXmlString(false);
        string prikey = rsa.ToXmlString(true);

        byte[] someThing = RSAEncrypt(Encoding.Unicode.GetBytes("Hello World"), pubkey);
        byte[] anotherThing = RSADecrypt(someThing, prikey);

        Console.WriteLine(Convert.ToBase64String(anotherThing));
    }

以及加密和解密函数

    public static byte[] RSAEncrypt(byte[] plaintext, string destKey)
    {
        byte[] encryptedData;
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        rsa.FromXmlString(destKey);
        encryptedData = rsa.Encrypt(plaintext, true);
        rsa.Dispose();
        return encryptedData;
    }

    public static byte[] RSADecrypt(byte[] ciphertext, string srcKey)
    {
        byte[] decryptedData;
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        rsa.FromXmlString(srcKey);
        decryptedData = rsa.Decrypt(ciphertext, true);
        rsa.Dispose();
        return decryptedData;
    }

我希望控制台显示 Hello World,但它显示这个 SABlAGwAbABvACAAVwBvAHIAbABkAA==。我是否错误地使用了 RSACryptoServiceProvider?

它是base 64,解码字符串你会得到"Hello world"。

你的最后一行应该是:

 Console.WriteLine(Encoding.Unicode.GetString(anotherThing));

目前您正在将解密后的字符串转为Base64编码