Monday, November 15, 2010

Decrypt a string using a specific given key

public static string Decrypt(string strEncrypted)
    {
      try
      {
        TripleDESCryptoServiceProvider objDESCrypto = new TripleDESCryptoServiceProvider();
        MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();

        byte[] byteHash, byteBuff;
        string strTempKey = _key;

        byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
        objHashMD5 = null;
        objDESCrypto.Key = byteHash;
        objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB

        byteBuff = Convert.FromBase64String(strEncrypted);
        string strDecrypted = ASCIIEncoding.ASCII.GetString(objDESCrypto.CreateDecryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
        objDESCrypto = null;

        return strDecrypted;
      }
      catch (Exception ex)
      {
        General.ExceptionOccured(ex);
        return "";
      }
    }

No comments:

Post a Comment