smokin' hash

November 29, 2007 under .NET, C++, MD5, PHP, Python

No, this post will make no mention of bottle tokes.

For the remaining freelance gig in my spare time pipeline (which hopefully is winding down), an ecommerce site, I had to create simple user management system. Obviously, I’m not going to store users’ passwords as plain text in the database, but rather as a hash – an MD5 hash to be exact. Unlike the old days where you had to implement the MD5 algorithm yourself, modern programming environments have this conveniently part of some specific standard library. From PHP, hashing a password (or any other string data) is easily accomplished like this:

$plain_text = "ChrisBellini.com";
$md5_text = md5($plain_text);
// hash is '56d1df360dce2f5025c71fa7697af642'

That hashed value is then stored in the database and I can use it to compare during logins. Easy peasy.

Sometimes, though, I’d like to verify what a hashed string really is. What does “12345” look like after passing through MD5? If you can do that in your head, then you can probably move objects with your mind. For those of us lowly creatures who can’t, though, a simple way to determine this would be nice. I’m a .NET guy in my day job, so a quick console app should suffice. Using .NET’s MD5 library with C# is trivial.

using System.Security.Cryptography;

// ...

string plain_text = "ChrisBellini.com";
UTF8Encoding objEnc = new UTF8Encoding();
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
byte [] arrHashBytes = md5Hasher.ComputeHash(objEnc.GetBytes(plain_text));
// hash is '56-D1-DF-36-0D-CE-2F-50-25-C7-1F-A7-69-7A-F6-42'

That would do the trick, but what if I’m on my Linux computer? I could use Mono, but still… It sure would be nice to be able to do this quickly on any operating system. Enter Python.

import hashlib
 
plain_text = "ChrisBellini.com"
md5_text = hashlib.md5(plain_text).hexdigest()
# hash is '56d1df360dce2f5025c71fa7697af642'

Pop this into Python’s interactive interpreter, Idle, and you’ve got yourself some lovely hash.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
comments: 0 »