Reputation: 504
If crypt()
generates a different string each time, how the heck am I supposed to combine a provided password and salt for the same encrypted password in the database?
I was thinking that I could generate a random salt for the crypt() method to combine with the users' provided input (id est crypt(@_POST['password'],$salt)
) for encrypting the password. That generates an encrypted password for my database. I'm also storing that $salt
in my database within a salt
column.
I thought that I could call crypt($_POST['providedPassword'],$saltStoredInDatabaseFromRegistrationTime)
to return the same encrypted value for the password I've stored in the database from the registration form, but it turns out that crypt()
is returning a different value every time I call it.
How am I supposed to end up with the same encrypted value I have in my database for the password?
Upvotes: 0
Views: 453
Reputation: 173522
The way crypt()
works is like this:
// to create
$hash = crypt($password, $salt);
// to verify
if (crypt($password, $hash) == $hash) {
// yay!
}
Not exactly like that; crypt()
has a variety of hash algorithms and it can return invalid hashes to indicate errors. Lastly, you should compare hashes using a comparison function that's not susceptible to timing attacks, such as the new hash_equals()
Note: It's important to always generate a new salt every time you hash something with crypt()
.
That said, since PHP 5.5 you should hash passwords using password_hash()
and password_verify()
; for earlier versions you can use the password_compat library.
Upvotes: 2