I want to store a (random) salt next to the password in the database. Now, the question is:
Should I store it hashed or in plain text? Is there any difference (more security, faster?)? An how much effort should I put in creating a random string?
Sample code:
//Creating random salt
$saltchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$%&()*+,-./:;<=>?@[]^_`{|}~";
$salt = uniqid(rand(), true).str_shuffle($saltchars);
// Or should the salt be hashed (md5 or sha512 for more security)
// $salt = hash('sha512', uniqid(rand(), true).$staticsalt.str_shuffle($saltchars));
//Create user (with salt & pepper)
$sqlquery = "INSERT INTO users (user, password, salt) VALUES('$id','".hash('sha512', $staticsalt.$accesskey.$salt)."','".$salt."');";
$sqlresult = mysql_query($sqlquery);
for the record: the login-script
$sqlquery = "SELECT salt FROM users WHERE user='$id';";
$sqlresult = mysql_query($sqlquery);
if (mysql_num_rows($sqlresult) == 1) {
$salt = (mysql_fetch_array($sqlresult));
//Check if the password is correct
$sqlquery = "SELECT * FROM users WHERE user='$id' AND password='".hash('sha512', $staticsalt.$accesskey.$salt[0])."'";
$sqlresult = mysql_query($sqlquery);
unset($accesskey, $salt);
//Check whether the query was successful or not
if($sqlresult) {
if(mysql_num_rows($sqlresult) == 1)
{echo 'Login successfull';}
else {die('Error: wrong user ID/password');}
}
}
I know that there are many, probably too many, websites out there discussing the pros & cons of a salt. But nobody answers if the salt should be encrypt or not – and nobody shows how to code a login script with random (!) salts (saved in the database as I did).
So as a php beginner I have no idea if this code is secure or not? Or if there are any tricks to make it faster or more streamlined… Thanks!
Since you need the salt to compute a password hash in the login script, you can’t just store the hash of the salt as this would be an irreversible operation, i.e. the original salt would be lost.
So I’m presuming you’re asking whether hashing the original salt obtained from picking a random string yields a better salt. In this case the use of a hashing function has nothing to do with ‘hashing’, it would just be a way to generate a longer, seemingly more random sequence. This makes absolutely no sense, however, as the hashed salt will still need to be stored in the database – in plaintext if you will!