问题
So, I successfully encrypt a password to password hash using this following code :
class PassHash
{
// blowfish
private static $algo = '$2a';
// cost parameter
private static $cost = '$10';
// mainly for internal use
public static function unique_salt()
{
return substr(sha1(mt_rand()), 0, 22);
}
// this will be used to generate a hash
public static function hash($password)
{
return crypt($password, self::$algo .
self::$cost .
'$' . self::unique_salt());
}
// this will be used to compare a password against a hash
public static function check_password($hash, $password)
{
$full_salt = substr($hash, 0, 29);
$new_hash = crypt($password, $full_salt);
return ($hash == $new_hash);
}
}
and this is how I encrypting the password :
$password_hash = PassHash::hash($user->getPasswordHash());
But I have a little problem now when I try to display the password in normal mode.
What is the best way to decrypt the password from that hash ?
回答1:
You can't decrypt a hash (well... technically you can, but you shouldn't) that's what hashes are for (not to be decrypted). You'll want to encrypt(hash) the password you received with the same hashing algorithm you used for the stored hash, and compare the hashes with eachother.
$password_hash = PassHash::hash($user->getPasswordHash());
if($stored_password === $password_hash){
//The passwords are the same
}
All in all you don't want to let anyone (not even yourself) know what the password of a user is (or the hash for that matter). The user will know, because he entered it and remembers it (hopefully anyway). No one else has got anything to do with seeing the user's password/hash. Letting anyone else but the user see/know the password/hash is a serious security issue.
On a different note: You should use the default implementations for hashing. Using your own hashing algorithm will always be worse than the true tried and tested methods. I'm not sure what PHP version you're using, but from PHP 5.5 onwards you can use password_hash(). For more information please view this question.
来源:https://stackoverflow.com/questions/28114384/php-decrypt-password-from-hash