开发者

PHP & MySQL Password Question

How can I add a salt to my current hash password when a user registers. And how should I 开发者_开发问答store to my password in My MySQL database?

Here is my PHP code so far.

if ($_POST['password1'] == $_POST['password2']) {
    $sha512 = hash('sha512', $_POST['password1']);
    $password = mysqli_real_escape_string($mysqli, $purifier->purify(strip_tags($sha512)));
} else {
    $password = NULL;
}


$salt = 'my-secret-salt-92h3nc29378ry293';

...

$sha512 = hash('sha512', $salt . $_POST['password1']);
$password = mysqli_real_escape_string($mysqli, $sha512);

To salt a password you simply concatenate it with another string (the salt) before hashing it. You also don't need to purify and exorcize the hashed password like you did, a hash won't contain anything bad.

You can use one salt for all passwords, which you should store somewhere centrally in your app. Alternatively, create a random salt for each password and save it alongside the hashed password in the database.


if ($_POST['password1'] == $_POST['password2']) {
    $sha512 = hash('sha512', $_POST['password1']."salt"); //<--------------------
    $password = mysqli_real_escape_string($mysqli, $purifier->purify(strip_tags($sha512)));
} else {
    $password = NULL;
}
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
$user = $_POST['user'];
$db = mysql_connect('host', 'user', 'password');
mysql_select_db('database', $db);
mysql_query("UPDATES user_table SET pass=$password WHERE user=$user");
mysql_close($db);


You can use algortithms like:

sha512($password.$salt) or sha512(sha512($password.$salt) It's up to you how the salt is generated, as long as its being stored alongside with the password hash in the database.


I like to store the salt with the password hash in the database and compute it like this:

$salt = "Su0";
$password = "mypassword0111";
$hash = md5(md5($password) . $salt);

Then when you login a user:

$sql = "SELECT * FROM user_table WHERE username = '...
//do db lookup
$hash = md5(md5($password_from_user_login) . $salt_from_db);
if($hash = $hash_from_db) {
  $userloggedin = true;
}

Or something like that

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜