I am a danish programmer living in Bangkok.
Read more about me @ rasmus.rummel.dk.
Webmodelling Home > ASP.NET > C# Utility Functions > String - Decrypt

Decrypt String

Decrypt is used to get back the original string after it have been encrypted using the Encrypt function - the Decrypt function MUST be given the same passphrase as was given to the Encrypt function - the passphrase is like a password we use to encrypt and decrypt string content.

Usage

  • Example
    • I use the Decrypt function in my FlexCaptcha WebControl on postback to decrypt the captcha letters stored in ViewState so I can compare the letters with the letters the user wrote in the captcha textbox.
  • Example Code
    • string myBankCode = "1234";
      string myEncryptedBankCode = Utils.String.Encrypt(myBankCode, "SomePassphrase");
      string myDecryptedBankCode = Utils.String.Decrypt(myEncryptedBankCode, "SomePassphrase"); //Passphrase MUST be identical to the passphrase used then encrypting
      
      myBankCode and myDecryptedBankCode is now identical.

The Decrypt function :

public static string Decrypt(string Message, string Passphrase)
{
	byte[] Results;
	System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
 
	// Step 1. We hash the passphrase using MD5
	// We use the MD5 hash generator as the result is a 128 bit byte array
	// which is a valid length for the TripleDES encoder we use below
 
	MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
	byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
 
	// Step 2. Create a new TripleDESCryptoServiceProvider object
	TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
 
	// Step 3. Setup the decoder
	TDESAlgorithm.Key = TDESKey;
	TDESAlgorithm.Mode = CipherMode.ECB;
	TDESAlgorithm.Padding = PaddingMode.PKCS7;
 
	// Step 4. Convert the input string to a byte[]
	byte[] DataToDecrypt;
	try
	{
		DataToDecrypt = Convert.FromBase64String(Message);
	}
	catch
	{
		return "ERROR";
	}
 
	// Step 5. Attempt to decrypt the string
	try
	{
		ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
		Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
	}
	finally
	{
		// Clear the TripleDes and Hashprovider services of any sensitive information
		TDESAlgorithm.Clear();
		HashProvider.Clear();
	}
 
	// Step 6. Return the decrypted string in UTF8 format
	return UTF8.GetString(Results);
}

Comments

You can comment without logging in
Profile
Username
Password
Password
Email
Nickpic
Get notified on reply to own posts  (only works if you specify an email address)
Get notified on receiving a PM  (only works if you specify an email address)
Remember my username
Remember my password
signature
Words: Chars: Chars left: