Encryption Using RSA in asp.net

Task: Encryption using RSA algorithm in asp.net.

Description: There are various Encryption-Decryption techniques. RSA is one of them. Encryption using RSA algorithm in asp.net. Here first we generate the key pair public-private key. Then we encrypt an de-crypt the data using keys.


using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;

public partial class rsaencryption : System.Web.UI.Page
{
  public void rsaencryption()
  {
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    string publicPrivateKeyXML = rsa.ToXmlString(true); // private key - Save it
    string publicOnlyKeyXML = rsa.ToXmlString(false);  // public key

    lbl_key.Text = publicPrivateKeyXML;

    string text = TextBox1.Text; // Plain Text
    rsa.FromXmlString(publicOnlyKeyXML);
    byte[] data = Encoding.UTF8.GetBytes(text);
    byte[] cipherText = rsa.Encrypt(data, false);

    Label2.Text = Convert.ToBase64String(cipherText); // Encrypted Data
  }
 
  public void rsadecryption()
  {
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    rsa.FromXmlString(lbl_key.Text); // Private Key as we generated at encryption

    byte[] ciphterText = Convert.FromBase64String(Label2.Text); // Encrypted Data
    byte[] plainText = rsa.Decrypt(ciphterText, false);
    Label3.Text = Encoding.UTF8.GetString(plainText); // Plain Text (Decrypted)
  }
}
 

No comments:

Post a Comment