Skip to content

Instantly share code, notes, and snippets.

@Maheshdeshmane
Last active June 18, 2020 10:43
Show Gist options
  • Save Maheshdeshmane/de4ed2b8dd15755c0b929ab3674d2c46 to your computer and use it in GitHub Desktop.
Save Maheshdeshmane/de4ed2b8dd15755c0b929ab3674d2c46 to your computer and use it in GitHub Desktop.
using System;
using System.Security.Cryptography;
using System.Text;
namespace AsymmetricCryptography
{
public class AsymmetricRsa
{
static void Main()
{
var rsaCryptoService = new RSACryptoServiceProvider();
var publicKey = rsaCryptoService.ToXmlString(false); // false to get the public key
var privateKey = rsaCryptoService.ToXmlString(true); // true to get the private key
Console.WriteLine("Enter message to encrypt");
var message = Console.ReadLine();
var encryptedMessage = EncryptMessage(publicKey, message, rsaCryptoService);
Console.WriteLine(new UnicodeEncoding().GetString(encryptedMessage));
var decryptData = DecryptData(privateKey,encryptedMessage);
Console.WriteLine(new UnicodeEncoding().GetString(decryptData));
Console.ReadLine();
}
static byte[] EncryptMessage(string publicKey, string message, RSACryptoServiceProvider rsaCryptoService)
{
var dataToEncrypt = new UnicodeEncoding().GetBytes(message);
rsaCryptoService.FromXmlString(publicKey);//We can even create new instance for RSACryptoServiceProvider
return rsaCryptoService.Encrypt(dataToEncrypt, false);
}
static byte[] DecryptData(string privateKey, byte[] dataToDecrypt)
{
var rsaCryptoService = new RSACryptoServiceProvider(); //a new instance for receiver;
rsaCryptoService.FromXmlString(privateKey);
return rsaCryptoService.Decrypt(dataToDecrypt, false);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment