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

Encrypt String

Cryptography have never been my strong side and looking for a simple EncryptString in .Net Framework is in vain - there are none. Instead I found a function on that internet which I copied directly into my utility library as is :


  • Example
    • I use the Encrypt function in my FlexCaptcha WebControl then storing the captcha letters in ViewState so that it is not possible to cheat the captcha by reading the ViewState client side.
  • 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 Encrypt function :

public static string Encrypt(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 encoder
	TDESAlgorithm.Key = TDESKey;
	TDESAlgorithm.Mode = CipherMode.ECB;
	TDESAlgorithm.Padding = PaddingMode.PKCS7;
	// Step 4. Convert the input string to a byte[]
	byte[] DataToEncrypt = UTF8.GetBytes(Message);
	// Step 5. Attempt to encrypt the string
		ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
		Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
		// Clear the TripleDes and Hashprovider services of any sensitive information
	// Step 6. Return the encrypted string as a base64 encoded string
	return Convert.ToBase64String(Results);

You can get the original string back using the Decrypt function.


You can comment without logging in
 B  U  I  S 
Words: Chars: Chars left: