Home > ASP.Net > Method to Encrypt and Decrypt

Method to Encrypt and Decrypt


Hi

try this example:

public class EncryptQueryString
 {
  public  string Decrypt( string stringToDecrypt)
  {
            stringToDecrypt= stringToDecrypt.Replace(" ", "+");
            string sEncryptionKey = "01234567890123456789";
   byte[] key = {};
   byte[] IV = {10, 20, 30, 40, 50, 60, 70, 80};
   byte[] inputByteArray = new byte[stringToDecrypt.Length];
   try
   {
    key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0,8));
    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
    inputByteArray = Convert.FromBase64String(stringToDecrypt);
    MemoryStream ms = new MemoryStream();
    CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
    cs.Write(inputByteArray, 0, inputByteArray.Length);
    cs.FlushFinalBlock();
    Encoding encoding = Encoding.UTF8 ;
    return encoding.GetString(ms.ToArray());
   }
   catch (System.Exception ex)
   {
      return (string.Empty);
   }
  }

 
public  string Encrypt( string stringToEncrypt)
  {
            string sEncryptionKey = "01234567890123456789";
   byte[] key = {};
   byte[] IV = {10, 20, 30, 40, 50, 60, 70, 80};
   byte[] inputByteArray; //Convert.ToByte(stringToEncrypt.Length)

   try
   {
    key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0,8));
    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
    inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
    MemoryStream ms = new MemoryStream();
    CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
    cs.Write(inputByteArray, 0, inputByteArray.Length);
    cs.FlushFinalBlock();
    return Convert.ToBase64String(ms.ToArray());
   }
   catch
   {
    return (string.Empty);
   }
  }
 }

Hope it helps

Good Luck

Advertisements
Categories: ASP.Net
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: