Friday, March 8, 2013

Sample program to Encrypt and Decrypt string using TripleDESCryptoServiceProvider in CSharp (C#)


When we developing a .NET application there may be a need to encrypt a string before it getting stored into the database. And also it can be Decrypted when the string retrieved back from the database. To achieve that refer the below code.

To Encrypt:
public string key = "ab99";  
public string encryption(string strToEncrypt)  
{  
     try  
     {  
          TripleDESCryptoServiceProvider DescCryptoprovider = new TripleDESCryptoServiceProvider();  
          MD5CryptoServiceProvider MD5serviceprovider = new MD5CryptoServiceProvider();  
          byte[] bytehash = null;  
          byte[] bytebuff = null;  
          bytehash = MD5serviceprovider.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));  
          MD5serviceprovider = null;  
          DescCryptoprovider.Key = bytehash;  
          DescCryptoprovider.Mode = CipherMode.ECB;  
          bytebuff = ASCIIEncoding.ASCII.GetBytes(strToEncrypt);  
          return Convert.ToBase64String(DescCryptoprovider.CreateEncryptor().TransformFinalBlock(bytebuff, 0, bytebuff.Length));  
     }  
     catch (Exception ex)  
     {  
          throw;  
     }  
}  

To Decrypt:
public string decrypt(string strTodecrypt)  
{  
     try  
     {  
          TripleDESCryptoServiceProvider DescCryptoprovider = new TripleDESCryptoServiceProvider();  
          MD5CryptoServiceProvider MD5serviceprovider = new MD5CryptoServiceProvider();  
          byte[] bytehash = null;  
          byte[] bytebuff = null;  
          string decryptedstring = null;  
   
          bytehash = MD5serviceprovider.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));  
          MD5serviceprovider = null;  
          DescCryptoprovider.Key = bytehash;  
          DescCryptoprovider.Mode = CipherMode.ECB;  
          bytebuff = System.Convert.FromBase64String(strTodecrypt);  
          decryptedstring = ASCIIEncoding.ASCII.GetString(
               DescCryptoprovider.CreateDecryptor().TransformFinalBlock(bytebuff, 0, bytebuff.Length)); 
 
          return decryptedstring;  
     }  
     catch (Exception ex)  
     {  
          throw;  
     }  
}  

1 comment: