Login / Create an Account

The Recipe for securely storing passwords in a database needs a little salt

Virtually all web applications that maintain some state for a user utilize a database to store credentials to authenticate the visitor. In a major step forward in security, developers have moved to storing a one-way hash of the user's password instead of the password itself. Rainbow tables and faster processors have given us a reason to include a little 'salt' into the procedure.

SHA1 and MD5 are the most common hashing functions used to obfuscate the password in the database. This has traditionally been considered a secure way to user credentials. With the advent of 'Rainbow Tables', this is no longer enough. Rainbow Tables are a time-space compromise. Instead of brute forcing individual every likely password is placed into a table along with its hash. After the tables have been completed, the table can be searched for the MD5 hashed password and the cleartext password will be evident.

The risk of exposing user credentials is now severe if someone is able to perform a dump of a table containing usernames and passwords. To combat this issue a technique was developed that introduces some noise along with the password before it is hashed. This noise is known as a 'salt'. Examples of running both a password and salted password through the MD5 functions are below:

/*This is an example of running a password through the MD5 function. */
$password = "mysecret";
$password = md5($password);


/*Here is how a salt would be added to the password before running through the function. */
$salt = "F$g%g4lq";
$password = "mysecret";
$password = md5($salt.$password);

In the second example, the salt is prepended to the password. This negates the benefits provided by the rainbow tables. The salt isn't limited to being before the password, it may be placed afterwards also. This flexibility, in addition, to modifying the salt string allows one to significantly increase the security of user credentials. The only way to regain the original password would be to know the salting procedure. If your site is particularly sensitive to privacy, the username could be salted also.