Advertisement
ivandrofly

Encryption/Decryption Function in .NET using the TripleDESCr

Mar 29th, 2014
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.89 KB | None | 0 0
  1. Encrypt function:
  2. public static string EncryptData(string Message)
  3. {
  4.     byte[] Results;
  5.     System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
  6.     MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
  7.     byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(passphrase));
  8.     TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
  9.     TDESAlgorithm.Key = TDESKey;
  10.     TDESAlgorithm.Mode = CipherMode.ECB;
  11.     TDESAlgorithm.Padding = PaddingMode.PKCS7;
  12.     byte[] DataToEncrypt = UTF8.GetBytes(Message);
  13.     try
  14.     {
  15.         ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
  16.         Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
  17.     }
  18.     finally
  19.     {                
  20.         TDESAlgorithm.Clear();
  21.         HashProvider.Clear();
  22.     }
  23.     return Convert.ToBase64String(Results);
  24. }
  25. Decrypt function:
  26. public static string DecryptString(string Message)
  27. {
  28.     byte[] Results;
  29.     System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
  30.     MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
  31.     byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(passphrase));
  32.     TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
  33.     TDESAlgorithm.Key = TDESKey;
  34.     TDESAlgorithm.Mode = CipherMode.ECB;
  35.     TDESAlgorithm.Padding = PaddingMode.PKCS7;
  36.     byte[] DataToDecrypt = Convert.FromBase64String(Message);
  37.     try
  38.     {
  39.         ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
  40.         Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
  41.     }
  42.     finally
  43.     {
  44.         TDESAlgorithm.Clear();
  45.         HashProvider.Clear();
  46.     }
  47.     return UTF8.GetString(Results);
  48. }
  49.  
  50. Note: read more in http://www.codeproject.com/Tips/306620/Encryption-Decryption-Function-in-Net-using-MD-Cry
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement