Thursday, July 30, 2009

Encrypt/Decrypt data in .Net

hi.

this is all about how to encrypt and decrypt string data using RijndaelManaged Class in .Net.
I will provide you whole class to perform encryption and decryption.

This is The Code.

using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;
public class CryptoUtils
{
const string Password = "
const string SaltValue = "_This_Is_My_Sault_";
RijndaelManaged RejManaged;
public CryptoUtils()
{
byte[] SaltBytes = Encoding.UTF8.GetBytes(SaltValue);
PasswordDeriveBytes password = new PasswordDeriveBytes(Password, SaltBytes);
RejManaged = new RijndaelManaged();
RejManaged.Key = password.GetBytes(RejManaged.KeySize / 8);
RejManaged.IV = password.GetBytes(RejManaged.BlockSize / 8);
}
public string EncryptText(string text)
{
try
{
byte[] inputByteArray = Encoding.UTF8.GetBytes(text);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, RejManaged.CreateEncryptor(), CryptoStreamMode.Write);
cryptoStream.Write(inputByteArray, 0, inputByteArray.Length);
cryptoStream.FlushFinalBlock();
return Convert.ToBase64String(memoryStream.ToArray());
}
#region Catch Exceptions
catch (Exception ex)
{
throw ex;
}
#endregion
}

public string DecryptText(string text)
{

try
{
MemoryStream memoryStream = new MemoryStream();
byte[] inputByteArray = Convert.FromBase64String(text);
CryptoStream cryptoStream = new CryptoStream(memoryStream, RejManaged.CreateDecryptor(), CryptoStreamMode.Write);
cryptoStream.Write(inputByteArray, 0, inputByteArray.Length);
cryptoStream.FlushFinalBlock();
return Encoding.UTF8.GetString(memoryStream.ToArray());
}
#region Catch Exceptions
catch (Exception ex)
{
throw ex;
}
#endregion
}
}

Create class file and paste above code in that file.
here is the sample code about how to Use this.

CryptoUtils objCryptoUtils = new CryptoUtils();
Response.Write(objCryptoUtils.EncryptText("Haresh?><)(*&^%$#@!"));
Response.Write("
");

Response.Write(objCryptoUtils.DecryptText(objCryptoUtils.EncryptText("Haresh?><)(*&^%$#@!")));

Thanks.