Validating passwords with random salts

喜你入骨 提交于 2019-12-08 06:20:57

问题


I have been trying to learn about hashes and salts stored in a users table withing a mysql DB. I get through with storing them but can't seem to wrap my head around how to validate when the user logs in.
I have looked through and seen about storing the salt and hash seperately and together. The salt that I am producing is random.

Any ideas?
I have posted my code.

<?php
$password = 'passwordwhatever';

//generate the salt
function gen_salt() {
    $salt = uniqid(mt_rand(), true) . sha1(uniqid(mt_rand(), true));
    $salt = crypt('sha512', $salt);
    return $salt;
}

//generate the hash
function gen_hash($salt, $password) {
    $hash = $salt . $password;
    for($i = 0; $i < 100000; $i++) {
        $hash = crypt('sha512', $hash);
    }

    $hash = $salt . $hash;
    return $hash;
}

$password = gen_hash(gen_salt(), $password);
echo $password;

?>

回答1:


As long as you produce the same salt, it shouldn't matter too much. Store it in your db, in configuration, as long as you can get to it. The effort of reversing a SHA512 hash is so high that unless you're the Pentagon, nobody will bother. The point is that you want to be able to repeat the hash with the same salt so you can be very sure that the input was the same without having to store the sensitive input. If that makes sense.




回答2:


The salt is going to need to be contained somewhere within the database (or somewhere). Some options are to append the salt to the hash or stored as its own field. I like appending it to the hash.

$password = $salt . '.' . $hash;

Then when the user goes to login, you grab his password, break it into the hash and the salt, and use your password generation function (with the salt from the password instead of a random salt) to determine if it matches the password in the db.

list($salt,$hash) = explode('.', $password);
$check = gen_hash($salt, $input_pass);
if ($check === $password)
    // valid



回答3:


Maybe you should take a look on bcrypt. This might help you. I wrote some tutorials but they are in german. Oh and PHP 5.3 support bcrypt natively.



来源:https://stackoverflow.com/questions/10890244/validating-passwords-with-random-salts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!