Monday, November 15, 2010

Encrypt a string using a given key?

 public static string Encrypt(string strToEncrypt)
    {
      try
      {
        TripleDESCryptoServiceProvider objDESCrypto = new TripleDESCryptoServiceProvider();
        MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();

        byte[] byteHash, byteBuff;
        string strTempKey = "Sameer";

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

        byteBuff = ASCIIEncoding.ASCII.GetBytes(strToEncrypt);
        return Convert.ToBase64String(objDESCrypto.CreateEncryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
      }
      catch (Exception ex)
      {
        General.ExceptionOccured(ex);
        return "";
      }
    }

No comments:

Post a Comment