RSA encryption/decryption C# example

There are two classes for asymmetric encryption in .net. RSACryptoServiceProvider and DSACryptoserviceProvider. With the default constructor, both classes automatically create the public and private keys necessary to encryption and decryption respectively. Call the ExportParameters function on either class which has a single boolean parameter to obtain the key. If true returns both public and private key

void Main()
{

	var keySize=2048;
	var rsaCryptoServiceProvider = new RSACryptoServiceProvider(keySize);

	var cipherText = Encrypt("hello world", rsaCryptoServiceProvider.ExportParameters(false));
	var plainText = Decrypt(cipherText, rsaCryptoServiceProvider.ExportParameters(true));
	Console.WriteLine(plainText);

}
public string Encrypt(string data, RSAParameters key)
{

	using (var rsa = new RSACryptoServiceProvider())
	{
		rsa.ImportParameters(key);
		var byteData = Encoding.UTF8.GetBytes(data);
		var encryptData = rsa.Encrypt(byteData, false);
		return Convert.ToBase64String(encryptData);
	}
}

public string Decrypt(string cipherText, RSAParameters key)
{

	using (var rsa = new RSACryptoServiceProvider())
	{
		var cipherByteData = Convert.FromBase64String(cipherText);
		rsa.ImportParameters(key);

		var encryptData = rsa.Decrypt(cipherByteData, false);
		return Encoding.UTF8.GetString(encryptData);
	}
}

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post