Windows Forms: Encryption and Decryption using RSA in C#

This post shows you how to encrypt and decrypt string using RSA algorithm in c# .net windows forms application.

As you know, algorithm c# rsa generate public and private key that helps you encryption and decryption in c# with key.

Drag the TextBox, Label and Button from the visual studio toolbox into your winform, then you can design a simple UI that allows you to encrypt and decrypt a string using the RSA algorithm in c# code as shown below.

encryption and decryption in c# with key

Through c# cryptography tutorial, we will create an Encrypt method to encrypt your data using RSA algorithm.

byte[] Encrypt(byte[] data, RSAParameters RSAKey, bool fOAEP)
{
    byte[] encryptedData;
    using (RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider())
    {
        rSACryptoServiceProvider.ImportParameters(RSAKey);
        encryptedData = rSACryptoServiceProvider.Encrypt(data, fOAEP);
    }
    return encryptedData;
}

Similarly, Create the Decrypt method to decrypt your data using RSA algorithm.

byte[] Decrypt(byte[] data, RSAParameters RSAKey, bool fOAEP)
{
    byte[] decryptedData;
    using (RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider())
    {
        rSACryptoServiceProvider.ImportParameters(RSAKey);
        decryptedData = rSACryptoServiceProvider.Decrypt(data, fOAEP);
    }
    return decryptedData;
}

Next, Declare unicodeEncodingrSACryptoServiceProviderdata and encryptData variables as shown below.

UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider();
byte[] data;
byte[] encryptData;

Finally, Use RSA to generate public and private key by calling the ExportParameters method.

rSACryptoServiceProvider.ExportParameters(false)

RSA algorithm performs encryption and decryption in c# with key.

Add the click event handler to the Encrypt button that allows you to encrypt data using RSA algorithm.

private void btnEncrypt_Click(object sender, EventArgs e)
{
    data = unicodeEncoding.GetBytes(txtInput.Text);
    encryptData = Encrypt(data, rSACryptoServiceProvider.ExportParameters(false), false);
    txtEncrypt.Text = unicodeEncoding.GetString(encryptData);
}

Add the click event handler to the Decrypt button allowing you to decrypt data.

private void btnDecrypt_Click(object sender, EventArgs e)
{
    byte[] data = Decrypt(encryptData, rSACryptoServiceProvider.ExportParameters(true), false);
    txtDecrypt.Text = unicodeEncoding.GetString(data);
}

You can create a web api or web services to support rsa encryption online.