Saturday, May 25, 2013

Encrypt and Decrypt string using C#.Net


Step-1: Use below given Namespace in your code file.

using System.Security.Cryptography;
using System.Text;
using System.IO;
 
Step-2: Add and call below method in your code to Encrypt string, this method accepts two parameter 1- String to be Encrypted 2- Key(A string of 16 numbers) and method will return encrypted string.

string Encryptor(string textToEncrypt, string key)
{
 RijndaelManaged rijndaelCipher = new RijndaelManaged();
 rijndaelCipher.Mode = CipherMode.CBC;
 rijndaelCipher.Padding = PaddingMode.PKCS7;
 rijndaelCipher.KeySize = 0x80;
 rijndaelCipher.BlockSize = 0x80;

 byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
 byte[] keyBytes = new byte[0x10];
 int len = pwdBytes.Length;
 if (len > keyBytes.Length)
 {
  len = keyBytes.Length;
 }

 Array.Copy(pwdBytes, keyBytes, len);
 rijndaelCipher.Key = keyBytes;
 rijndaelCipher.IV = keyBytes;

 ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
 byte[] plainText = Encoding.UTF8.GetBytes(textToEncrypt);
 return Convert.ToBase64String(transform.TransformFinalBlock(plainText, 0,      plainText.Length));
}


Step-3: Add and call below method in your code to Decrypt string, this method accepts two parameter 1- String to be Decrypted 2- Key(Which is used to encrypt string in above method) and method will return decrypted string.

 string Decryptor(string textToDecrypt, string key)
{
  RijndaelManaged rijndaelCipher = new RijndaelManaged();
  rijndaelCipher.Mode = CipherMode.CBC;
  rijndaelCipher.Padding = PaddingMode.PKCS7;
  rijndaelCipher.KeySize = 0x80;
  rijndaelCipher.BlockSize = 0x80;

  byte[] encryptedData = Convert.FromBase64String(textToDecrypt);
  byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
  byte[] keyBytes = new byte[16];
  int len = pwdBytes.Length;
  if (len > keyBytes.Length)
 {
   len = keyBytes.Length;
 }

 Array.Copy(pwdBytes, keyBytes, len);
 rijndaelCipher.Key = keyBytes;
 rijndaelCipher.IV = keyBytes;

 byte[] plainText = rijndaelCipher.CreateDecryptor().TransformFinalBlock(encryptedData, 0,  encryptedData.Length);
 return Encoding.UTF8.GetString(plainText);
}

No comments:

Post a Comment