简体   繁体   中英

RSACryptoServiceProvider encrypt and decrypt using own public and private key

I'm told that for asymmetric cryptography you encrypt plaintext with your public key and decrypt it with your private key. So i've tried the following:

    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));
    }

and the encrypt and decrypt functions

    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;
    }

I'm expecting the console to display Hello World , but it displays this SABlAGwAbABvACAAVwBvAHIAbABkAA== . Am i using RSACryptoServiceProvider wrongly?

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

Your last line should read:

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

Currently you are converting the decrypted string to Base64 encoding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM