Encrypt and decrypt plain string with triple DES in C#

We looked at encryption mechanisms in details on this blog – refer to the link at the end of this post. This is only a quick extension showing how to encrypt a plain string using Triple DES.

Consider the following method which encrypts a plain string with a key a cipher mode ECB:

public string Encrypt(string source, string key)
{
	TripleDESCryptoServiceProvider desCryptoProvider = new TripleDESCryptoServiceProvider();
	MD5CryptoServiceProvider hashMD5Provider = new MD5CryptoServiceProvider();

	byte[] byteHash;
	byte[] byteBuff;

	byteHash = hashMD5Provider.ComputeHash(Encoding.UTF8.GetBytes(key));
	desCryptoProvider.Key = byteHash;
	desCryptoProvider.Mode = CipherMode.ECB; //CBC, CFB
	byteBuff = Encoding.UTF8.GetBytes(source);

	string encoded = 
		Convert.ToBase64String(desCryptoProvider.CreateEncryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
	return encoded;
}

If you call the above method as follows…:

String encoded = Encrypt("hello world", "mykey");

…”encoded” will be hSyClKJMttMuvMs+Du7R3w==

You can decrypt this string using the following function:

public static string Decrypt(string encodedText, string key)
{
	TripleDESCryptoServiceProvider desCryptoProvider = new TripleDESCryptoServiceProvider();
	MD5CryptoServiceProvider hashMD5Provider = new MD5CryptoServiceProvider();

	byte[] byteHash;
	byte[] byteBuff;

	byteHash = hashMD5Provider.ComputeHash(Encoding.UTF8.GetBytes(key));
	desCryptoProvider.Key = byteHash;
	desCryptoProvider.Mode = CipherMode.ECB; //CBC, CFB
	byteBuff = Convert.FromBase64String(encodedText);

	string plaintext = Encoding.UTF8.GetString(desCryptoProvider.CreateDecryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
	return plaintext;
}

Call it like…

String plain = Decrypt(encoded, "mykey");

…and “plain” will be “hello world” as expected.

You can view the list of posts on Security and Cryptography here.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

5 Responses to Encrypt and decrypt plain string with triple DES in C#

  1. Pingback: Encrypt and decrypt plain string with triple DES in C# | Dinesh Ram Kali.

  2. Sridhar says:

    Pl. check with the site.. https://www.tools4noobs.com/online_tools/decrypt/
    The encryption is differing..

  3. Roberto says:

    wonderful, thank you very much , useful

  4. Vlad says:

    You implementation is not compatible with CBC, as it is not providing a VI to the “desCryptoProvider” object. Without that, this object in the Decrypt method is not aware which VI to use.

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.