If you use the php5.5 version, our hash creation and verification methods are much simpler. PHP 5.5 provides us with 4 functions: password_get_info(), password_hash(), password_needs_rehash(), and password_verify() , with these four we can quickly implement hash creation and verification.
First discuss the password_hash() function. This will be used as the hash value to create a new password. It contains three parameters: password, hash algorithm, options. The first two items are required. You can use this function according to the following example:
The code is as follows | Copy code | ||||
$hash = password_hash($password,PASSWORD_BCRYPT); //$2y$10$uOegXJ09qznQsKvPfxr61uWjpJBxVDH2KGJQVnodzjnglhs2WTwHu
|
代码如下 | 复制代码 |
$options = [ 'cost' => 10, 'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM) ]; |
After adding the option to the password_hash() function, our hash value changes and is more secure.
代码如下 | 复制代码 |
$hash = password_hash($password,PASSWORD_BCRYPT,$options); //y$JDJ5JDEwJDhsTHV6SGVIQuprRHZnGQsUEtlk8Iem0okH6HPyCoo22 |
Now that the hash is created, we can view information about the new hash value through password_get_info(). password_get_info() takes one argument - the hash value - and returns a parameter containing the algorithm (an integer representation of the hashing algorithm used), the algorithm name (the human-readable name of the hashing algorithm used), and the options we used to create the hash associative array of value options).
代码如下 | 复制代码 |
var_dump(password_get_info($hash)); /* array(3) { ["algo"]=> int(1) ["algoName"]=> string(6) "bcrypt" ["options"]=> array(1) { ["cost"]=> int(10) } } |
*/The first one added to the Password Hashing API is password_needs_rehash(), which accepts three parameters, hash, hash algorithm and options. The first two are required. password_needs_rehash() is used to check whether a hash value was created using a specific algorithm and options. This is useful if your database is damaged and you need to adjust the hash. By checking each hash value with password_needs_rehash(), we can see whether the existing hash value matches the new parameter, affecting only those values created with the old parameter.
Finally, we have created our hash, looked up how it was created, checked whether it needs to be re-hashed, now we need to verify it. To verify plain text to its hash value, we must use password_verify(), which takes two parameters, password and hash value, and will return TRUE or FALSE. Let's check the hashed we got to see if it's correct.
The code is as follows
|
Copy code
|
||||
$authenticate = password_verify('foo','$2y$10$JDJ5JDEwJDhsTHV6SGVIQuprRHZnGQsUEtlk8Iem0okH6HPyCoo22');
| Example
The code is as follows
|
Copy code |