Nerdrium Home



Web Design

Case Mods





My Blog




Using MD5 Encryption for Passwords

by Michael Greifenkamp (June 25th, 2007)

My job requires me to be very careful with the way I store any sensitive data on a web server. Fortunately, I don't have to deal with keeping social security numbers safe or anything that sensitive. About the only thing I have are some user names and passwords and such.

The best way, I've found, to safely keep passwords stored in a database is to encrypt them. And to remove myself from the equation (that is, making it so even I can't access user's passwords) is to encrypt them using a one-way hash.

I'm not an expert on encryption, of course, but basically, hashing a string or password or whatever using MD5 returns a 32-digit hexadecimal value. The thing to remember is that once something is hashed using MD5, you can't get the original value back.

But here's the idea: when you want to write a password into a database field, get the MD5 value and write that to the database instead. Then when you want to check the password, take whatever the user enters, MD5 hash that, and compare the result with what is stored in the database. If they enter the correct password, the two strings will match.

Here's a MySQL query (with PHP variables) to write the MD5 value to the database:

INSERT INTO users VALUES('','$username',MD5('$userpassword'));

In ColdFusion you might do this instead:

INSERT INTO users VALUES ('','#Form.username#',MD5('#Form.userpassword#'));

Now when you want to check a password that a user has entered into a web form, maybe that allows them to log into a private set of web pages or something, you can do the following:

SELECT id FROM users WHERE username='$username' AND userpassword=MD5('$userpassword');

Or in ColdFusion:

SELECT id FROM users WHERE username='#Form.username#' AND userpassword=MD5('#Form.userpassword#');

The thing to remember here, however, is that if a user loses/forgets their password, it's gone. And you don't have any way to get it back for them. All you can do at this point is reset their password to something else, write the MD5 value of that to the database, and e-mail them what the new password is. Then you might have a web page where they can enter the password you generated for them and change it to something else.

Let me know if you have any questions.