Encrypt and Decrypt strings in Dot Net for Sensitive Data Like Passwords  

by ne on 2020-12-02 under Asp.net

Encryption Method:

public string Encrypt(string secureUserData , bool useHashing)

{

    byte[] keyArray;

    byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(secureUserData );

    string key = string.Empty;

    byte[] resultArray;

    key = ConfigurationManager.AppSettings.Get("SecurityKey");

    if (useHashing)

    {

        MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();

        keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));

        hashmd5.Clear();

    }

    else

    {

        keyArray = UTF8Encoding.UTF8.GetBytes(key);

    }

    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

    tdes.Key = keyArray;

    tdes.Mode = CipherMode.ECB;

    tdes.Padding = PaddingMode.PKCS7;

    ICryptoTransform cTransform = tdes.CreateEncryptor();

    resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

    tdes.Clear();

    return Convert.ToBase64String(resultArray, 0, resultArray.Length);

}

Decryption Method:

public string Decrypt(string cipherString, bool useHashing)

{

    byte[] keyArray;

    byte[] toEncryptArray = Convert.FromBase64String(cipherString);

    byte[] resultArray;

    string key = string.Empty;

    key = ConfigurationManager.AppSettings.Get("SecurityKey");  // Get the key from Web.Config file

    if (useHashing)

    {

        MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();

        keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));

        hashmd5.Clear();

    }

    else

    {

        keyArray = UTF8Encoding.UTF8.GetBytes(key);

    }

    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

    tdes.Key = keyArray;

    tdes.Mode = CipherMode.ECB;

    tdes.Padding = PaddingMode.PKCS7;

    ICryptoTransform cTransform = tdes.CreateDecryptor();

    resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

    tdes.Clear();

    return UTF8Encoding.UTF8.GetString(resultArray);

}


thanks