Salting Passwords with php
i'm currently working on a project for a client where i will be salting a password and storing the resulting hash. before this project i was only vaguely familiar with the concept and it turns out it's not hard. before the snippet of code, a basic preface: huh?
the idea is to hash together a randomly generated string with the users password, then store the resulting hash and the random string in the database, so you never actually store the users password. then the user then tries to login, you retrieve the hash and the salt, hash together the salt and the user supplied password, and compare the result to the stored hash. if they match, consider the user authenticated. for a much more detailed explanation, see here.
now some code:
// get user password from $_POST[]
$newPassword = $_POST['new_password'];
// generate a 32 character hash by hashing a random number between 1 - 10,000
$salt = md5(rand(1,10000));
// hash the two together, store this result.
$new_password_hash = md5($salt.$newPassword)
now on login, retieve the users password hash and password salt, and compare the hash of the supplied password with the password salt to the stored hash:
$login_query = sprintf("SELECT u.password_hash,
u.password_salt
FROM Users u
WHERE u.username = '%s' LIMIT 1", mysql_escape_string($_POST['username']));
$login_results = mysql_query($login_query, $db) or die(mysql_error());
$user_row = mysql_fetch_assoc($login_results);
if($user_row['password_hash'] == md5($user_row['password_salt'].$_POST['password'])) {
// user is authenticated
} else {
// user is not authenticated
}