C#.NET Encryption RSA Technology

How to RSA Encrypt Decrypt Data (C#) ?

This post has reference to part one of this Article.

Inside our “Crypt” class, lets include two more methods.

public string EncryptData(string data2Encrypt)
{
      ParameterSetup();
      StreamReader reader = new StreamReader(publicPath);
      string publicOnlyKeyXML = reader.ReadToEnd();
      rsa.FromXmlString(publicOnlyKeyXML);
      reader.Close();

 

      //encrypt
      byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt);
      byte[] cipherbytes = rsa.Encrypt(plainbytes, false);
      return Convert.ToBase64String(cipherbytes);
}

public string DecryptData(string data2Decrypt)
{
      ParameterSetup();

      byte[] getpassword = Convert.FromBase64String(data2Decrypt);

      StreamReader reader = new StreamReader(privatePath);
      string publicPrivateKeyXML = reader.ReadToEnd();
      rsa.FromXmlString(publicPrivateKeyXML);
      reader.Close();

      //decrypt
      byte[] plain = rsa.Decrypt(getpassword, false);
      return System.Text.Encoding.UTF8.GetString(plain);
}

Now from Aspx page you can use these methods as follows,

Crypt myCrypt = new Crypt();
myCrypt.updatePrivatePath(Server.MapPath(“PrivateKey.xml”));
myCrypt.updatePublicPath(Server.MapPath(“PublicKey.xml”));

 

myCrypt.GenerateKey();

 
 
string EncryptData = myCrypt.EncryptData(“Your Name”);
string DecryptData = myCrypt.DecryptData(EncryptData);

 

 

 

 
Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *