Store Your passwords with Salts

This isn’t a new practice by any means, if your PHP developer is worth their salt they will recommend relying on a third party to authenticate users like Facebook or Twitter whenever possible. What about the times when you can’t rely on third parties to authenticate your users?

After the Gawker incident there was a large push for better password storage practices. Here’s a fairly safe way to store passwords if you must:

<?php
define('SALT_LENGTH', 9);

function generateHash($plainText, $salt = null)
{
    if ($salt === null)
    {
        $salt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH);
    }
    else
    {
        $salt = substr($salt, 0, SALT_LENGTH);
    }

    return $salt . sha1($salt . $plainText);
}
?>

It uses what’s know as a “salt” to add length and randomness to a password string. This “salted string” contains both the users’s password and the salt encrypted together to make rainbow cracking this hash a very laborious task. It’s called a one way function in that the result is hard to invert without knowing some “secret” portion of the equation.

Leave a Reply

Your email address will not be published. Required fields are marked *