Encrypt and decrypt plain string with triple DES in C#
October 23, 2015 5 Comments
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.
Pingback: Encrypt and decrypt plain string with triple DES in C# | Dinesh Ram Kali.
Pl. check with the site.. https://www.tools4noobs.com/online_tools/decrypt/
The encryption is differing..
i don’t know how that tool implements encryption – other than that it uses a PHP function – so it’s difficult to comment.
//Andras
wonderful, thank you very much , useful
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.