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!
It doesn't matter. You can assume the salt is public information, since the attack the salt helps protect against -- rainbow-table assisted dictionary attacks -- isn't made any easier if the salt is known by the attacker. You should ask yourself why you think it's a good idea to encrypt the salt in the first place.
Also, you should read this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With