Encrypt and Decrypt Text Values in .NET

Encrypt and Decrypt Text Values in .NET

In this article, we will explore how to encrypt/decrypt text using .NET and MD5 crypto provider. These methods can be used to secure critical values that are used by our ASP.NET web application. 

As you may know, .NET provides different ways to encrypt and then decrypt text values. However, in this article we will use the "MD5CryptoServiceProvider" and "TripleDESCryptoServiceProvider" to encrypt our text values. Usually, these encryption and decryption methods are very useful to store user data in an encrypted format. 

For storing password, we should use hashing mechanism that is not reversible. Otherwise, anyone can decrypt the password and get the actual format.

In our utility class, we have the Encrypt method that takes the clear text as an input parameter and returns the encrypted string. Let's explore the code of this method:

.NET Encrypt Method

public static string Encrypt(string stringToEncrypt)
{
    if (!string.IsNullOrEmpty(stringToEncrypt))
    {
        byte[] keyArray;
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(stringToEncrypt);

        System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
        // Get the key from config file

        string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));
        
        //If hashing use get hashcode regards to your key
        MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
        keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        //Always release the resources and flush data
        // of the Cryptographic service provide. Best Practice

        hashmd5.Clear();

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        //set the secret key for the tripleDES algorithm
        tdes.Key = keyArray;
        //mode of operation. there are other 4 modes.
        //We choose ECB(Electronic code Book)
        tdes.Mode = CipherMode.ECB;
        //padding mode(if any extra byte added)

        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateEncryptor();
        //transform the specified region of bytes array to resultArray
        byte[] resultArray =
            cTransform.TransformFinalBlock(toEncryptArray, 0,
            toEncryptArray.Length);
        //Release resources held by TripleDes Encryptor
        tdes.Clear();
        //Return the encrypted data into unreadable string format
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }
    return "";
}

In the same manner, we have the Decrypt method that takes the cipher text as an input parameter and returns the clear text. Let's explore the code of this method:

.NET Decrypt Method

public static string Decrypt(string cipherString)
{
    if(!string.IsNullOrEmpty(cipherString))
    {
        byte[] keyArray;
        //get the byte code of the string

        byte[] toEncryptArray = Convert.FromBase64String(cipherString.Replace(" ", "+"));

        System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
        //Get your key from config file to open the lock!
        string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));

        //if hashing was used get the hash code with regards to your key
        MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
        keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        //release any resource held by the MD5CryptoServiceProvider

        hashmd5.Clear();

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        //set the secret key for the tripleDES algorithm
        tdes.Key = keyArray;
        //mode of operation. there are other 4 modes. 
        //We choose ECB(Electronic code Book)

        tdes.Mode = CipherMode.ECB;
        //padding mode(if any extra byte added)
        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateDecryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(
                                toEncryptArray, 0, toEncryptArray.Length);
        //Release resources held by TripleDes Encryptor                
        tdes.Clear();
        //return the Clear decrypted TEXT
        return UTF8Encoding.UTF8.GetString(resultArray);
    }
    return "";
}

Conclusion

In this article, we shared two .NET methods that allow us to encrypt and again decrypt any text value.

Post a Comment

Previous Post Next Post