RSA encryption/decryption C# example

In this blog post I will discuss about encryption and decryption in C#. There are a lot of algorithms for encryptiong and decrypting the data but here I am going to discuss about RSA encryption algorithm.
By the end of this blog post you will be get familar with the following things

  • What is encryption?
  • How to encrypt and decrypt data in C# using RSA algorithms

What is Encryption?

Data encryption is the process of converting data into a form that cannot be read by anyone except those who are authorized to do so. Data encryption is used for the following reasons:

  • Protecting the confidentiality of sensitive or classified information

  • Detecting and preventing tampering, e.g., to ensure a document has not been changed after being sent

  • Establishing digital identity; use in public key infrastructure, which verifies whether someone is who they claim to be

Types of Encryption

Encryption can take many forms and be used for many purposes. However, there are two broad categories that are most often discussed: symmetric key cryptography and asymmetric key cryptography. Symmetric-key encryption uses a single private key with which both parties share parameters (symmetric keys) to encrypt and decrypt messages securely. Asymmetric-key encryption uses two related keys, one of which is secret (private) and one of which is public. The public key can be distributed publicly without jeopardizing security because

How to encrypt and decrypt data using RSA Algorithm in C#

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