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?
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.
Public Key (or asymmetric encryption) In a public key system, two keys are used, one for encrypting and one for decrypting.
Public key encryption is also called asymmetric encryption, because the same key cannot be used to encrypt and decrypt the message.
It is base 64, decode the string and you will get "Hello world".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With