Encrypt and Decrypt a String in C# Using Asymmetric Encryption

In .NET, there are two classes available for asymmetric encryption: RSACryptoServiceProvider and DSACryptoServiceProvider. These classes automatically generate the necessary public and private keys for encryption and decryption when using the default constructor. To obtain the key, you can call the ExportParameters function on either class, which takes a single boolean parameter. If the parameter is set to true, it will return both the public and private keys.

Here’s an example code snippet that demonstrates the usage of RSACryptoServiceProvider for encryption and decryption:

$ads={1}

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);
	}
}

In the above code, we create an instance of RSACryptoServiceProvider with the desired key size. The Encrypt method takes the plaintext and the public key obtained from ExportParameters(false) to encrypt the data. Similarly, the Decrypt method uses the ciphertext and the private key obtained from ExportParameters(true) to decrypt the data.

By following these steps, you can perform asymmetric encryption and decryption using RSACryptoServiceProvider in .NET.

Please note that the code snippet provided is for demonstration purposes and may require additional error handling and security measures when used in production environments.

Post a Comment

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

Previous Post Next Post

Blog ads

CodeGuru