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

Mon*_*iro 6 c# encryption cryptography rsa

有人告诉我,对于非对称加密,你用你的公钥加密明文,然后用你的私钥解密。所以我尝试了以下方法:

    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));
    }
Run Code Online (Sandbox Code Playgroud)

以及加密和解密功能

    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;
    }
Run Code Online (Sandbox Code Playgroud)

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

Bla*_*214 6

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