MD5 in one line of C# code.

Considering the popularity of using MD5 to hash passwords in a database, I’m litterally baffled as to why Microsoft didn’t include a System.Security.Cryptography.MD5() function. This isn’t quite as nice as that would be, but it gets the job done:

string hash = Convert.ToBase64String(new System.Security.Cryptography.MD5CryptoServiceProvider().

Pretty much every other example I’ve seen are at least 10 lines. The only difference here is that this one returns a string in base64, where most others return a string of hex digits concatenated togeter. That shouldn’t matter if all you’re doing is hashing passwords, but probably won’t do if you plan to share the hash with someone else for varification that a file matches a certain signature.

I’ve created a Visual Studio 2005 snippet file which you can import, then just type md5{TAB}{TAB} to have the code appear.

If you’re concerned about the status of MD5 and it’s use of a hash function, read How to break MD5 and Other Hash Functions [PDF] by Xiaoyun Wang and Hongbo Yu. Realize that the attack they describe is only theoretical, and can’t be used to derrive a password from it’s MD5 hash, nor can it be used to create another password which matches a given hash. So MD5 is still as secure as ever for use as a password hash function.