Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 797
MonoShiro Avatar asked Jan 05 '16 14:01

MonoShiro


People also ask

Can you encrypt with private key and decrypt with public key?

Asymmetric encryption uses a mathematically related pair of keys for encryption and decryption: a public key and a private key. If the public key is used for encryption, then the related private key is used for decryption. If the private key is used for encryption, then the related public key is used for decryption.

Can public key be used for both encryption and decryption?

Public Key (or asymmetric encryption) In a public key system, two keys are used, one for encrypting and one for decrypting.

Can I decrypt using public key?

Public key encryption is also called asymmetric encryption, because the same key cannot be used to encrypt and decrypt the message.


1 Answers

It is base 64, decode the string and you will get "Hello world".

like image 121
Blady214 Avatar answered Nov 14 '22 23:11

Blady214