using sha256 as hashing and salting with user'

2019-03-02 15:55发布

问题:

I'm gonna use sha256 for my site,to secure my users passwords,and as salt i was thinking of usings the users id (int auto_increment). that will be unique but not very long and hard,and public(user.php?id=1) but it just matters if its unique right?

hash('sha256', $id . $password);

回答1:

Yes, it is important that the salt is unique (collissions sufficiently unlikely), but it should also have enough entropy (be random and long enough). User ids are not random and may be too short, so your best bet is to use randomly generated strings and store them in your database alongside the hash.

Suppose a user with UID 9 chooses a stupid password: password. The resulting string that will be hashed may then be 9password. You can imagine that even in this case, the full string may appear in rainbow tables (tables which contain lots and lots of hashes with their original string).

If the salt in this case would be, for example, OTAzMzYzODQzMjk5NTM1NDc1N, the string to be hashed is OTAzMzYzODQzMjk5NTM1NDc1Npassword, which is a lot more unlikely to appear in rainbow tables. Also, the input strings are a lot longer, reducing the risk of brute force attacks.



回答2:

This would work but the purpose of using salt is to differentiate the hash key to strengthen the crypt algorithm. It would be much better to use a unique, random generated / time salted string for salt. Also it would be better not to include the salt and hash key in the same table.



回答3:

Your salt should not be easily guessable. In one of it's more basic forms, you could simply create a salt based on the current TIMESTAMP using

   date('U')

which is far more secure due to its length, uniqueness, and the fact that you store it in the DB and don't make it publicly available. You would then utilize it in such a manner:

$hash = date('U');
$pass = hash('sha256', $hash . $password);

and as far as checking passwords on login:

// return query object based on matching email/username
if ($userobj->pass === hash('sha256', $userobj->salt .$_POST['pass'])) {
    // correct pass
}


回答4:

I don't think that is a good choice: I would use a more random salt saving it into the user record. Maybe saving in the password field this string: sha256($password . $randomSalt) . '$' . $randomSalt

This way you can then retrieve the salt to check the passoword on login.

(Anyway you can also use another field for the salt alone)



标签: php hash