ScotlandPHP 2019

password_hash

(PHP 5 >= 5.5.0)

password_hashCreates a password hash

Opis

string password_hash ( string $password , integer $algo [, array $options ] )

password_hash() creates a new password hash.

Parametry

password

The user's password.

algo

A password algorithm constant denoting the algorithm to use when hashing the password.

options

An associative array containing options. Currently, two options are supported: salt, to provide a salt to use when hashing the password, and cost, which denotes the algorithmic cost that should be used. Examples of these values can be found on the crypt() page.

If omitted, a random salt will be created and the default cost will be used.

Zwracane wartości

Returns the hashed password, lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 password_hash() example

<?php
echo password_hash("rasmuslerdorf"PASSWORD_DEFAULT)."\n";

$options = [
    
'cost' => 7,
    
'salt' => 'BCryptRequires22Chrcts',
];
echo 
password_hash("rasmuslerdorf"PASSWORD_BCRYPT$options)."\n";
?>

Powyższy przykład wyświetli:

$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a
$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq

add a note add a note

User Contributed Notes 12 notes

up
153
martinstoeckli
6 years ago
There is a compatibility pack available for PHP versions 5.3.7 and later, so you don't have to wait on version 5.5 for using this function. It comes in form of a single php file:
https://github.com/ircmaxell/password_compat
up
41
nicoSWD
5 years ago
I agree with martinstoeckli,

don't create your own salts unless you really know what you're doing.

By default, it'll use /dev/urandom to create the salt, which is based on noise from device drivers.

And on Windows, it uses CryptGenRandom().

Both have been around for many years, and are considered secure for cryptography (the former probably more than the latter, though).

Don't try to outsmart these defaults by creating something less secure. Anything that is based on rand(), mt_rand(), uniqid(), or variations of these is *not* good.
up
39
Cloxy
5 years ago
You can produce the same hash in php 5.3.7+ with crypt() function:

<?php

$salt
= mcrypt_create_iv(22, MCRYPT_DEV_URANDOM);
$salt = base64_encode($salt);
$salt = str_replace('+', '.', $salt);
$hash = crypt('rasmuslerdorf', '$2y$10$'.$salt.'$');

echo
$hash;

?>
up
1
sasonxg at gmail dot com
5 months ago
Please, its important that you take note of the documentation as regards the length of the password character on the database. Using  password_verify to resolve a password that is hashed using the password_hash function, when the password is set to 50, it might show some malfunctioning. As the documentation shows, the lenght can change. So, to be on the safer side, set the length to 255.
up
14
Lyo Mi
3 years ago
Please note that password_hash will ***truncate*** the password at the first NULL-byte.

http://blog.ircmaxell.com/2015/03/security-issue-combining-bcrypt-with.html

If you use anything as an input that can generate NULL bytes (sha1 with raw as true, or if NULL bytes can naturally end up in people's passwords), you may make your application much less secure than what you might be expecting.

The password
$a = "\01234567";
is zero bytes long (an empty password) for bcrypt.

The workaround, of course, is to make sure you don't ever pass NULL-bytes to password_hash.
up
11
Mike Robinson
4 years ago
For passwords, you generally want the hash calculation time to be between 250 and 500 ms (maybe more for administrator accounts). Since calculation time is dependent on the capabilities of the server, using the same cost parameter on two different servers may result in vastly different execution times. Here's a quick little function that will help you determine what cost parameter you should be using for your server to make sure you are within this range (note, I am providing a salt to eliminate any latency caused by creating a pseudorandom salt, but this should not be done when hashing passwords):

<?php
/**
* @Param int $min_ms Minimum amount of time in milliseconds that it should take
* to calculate the hashes
*/
function getOptimalBcryptCostParameter($min_ms = 250) {
    for (
$i = 4; $i < 31; $i++) {
       
$options = [ 'cost' => $i, 'salt' => 'usesomesillystringforsalt' ];
       
$time_start = microtime(true);
       
password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);
       
$time_end = microtime(true);
        if ((
$time_end - $time_start) * 1000 > $min_ms) {
            return
$i;
        }
    }
}
echo
getOptimalBcryptCostParameter(); // prints 12 in my case
?>
up
9
martinstoeckli
5 years ago
In most cases it is best to omit the salt parameter. Without this parameter, the function will generate a cryptographically safe salt, from the random source of the operating system.
up
0
VladimirMozhenkov at yahoo dot com
3 years ago
Note that this function can return NULL. It does so if you provide an incorrect constant as an algorythm. I had the following:

    $password = password_hash($password1, PASSWORD_BDCRYPT, array( 'cost' => 10 ));

and i couldn't understand why i kept having NULL written in $password; it was a simple fact that the constant was PASSWORD_BCRYPT.
up
0
cottton
4 years ago
if you thought
"why is the salt included in the hash and is it save when i store it as it is in my db?"

Answer i found:
The salt just has to be unique. It not meant to be a secret.

As mentioned in notes and docu before: let password_hash() take care of the salt.

With the unique salt you force the attacker to crack the hash.
The hash is unique and cannot be found at rainbow tables.
up
-2
anonymous
3 years ago
Pay close attention to the maximum allowed length of the password parameter!  If you exceed the maximum length, it will be truncated without warning.

If you prepend your own salt/pepper to the password, and that salt/pepper exceeds the maximum length, then this function will truncate the actual password.  That means password_verify() will return true with ANY password using the same salt/pepper.

It might be a good idea to append any salt/pepper to the end of the password instead.
up
-4
omidbahrami1990 at gmail dot com
1 year ago
This Is The Most Secure Way To Hash Password,
Here Salt Will Be Automatically Generated,
Cost Will Be 10 Which Is Secure And Fast Enough.

<?php
function secured_hash($input)
{   
$output = password_hash($input,PASSWORD_DEFAULT);
return
$output;
}

/*
$input ---> Is The String You Want To Hash

PASSWORD_DEFAULT ---> It Means Use The Lastest And Strongest Algorithm To Hash

$output ---> Is The Hashed String You Can Store In Your Database
*/
?>
up
-40
darkflib
2 years ago
Timings:

Note: 1 and 2 for cost are invalid.

3  -  0.085115432739258ms
4  -  1.6319751739502ms
5  -  2.9170513153076ms
6  -  5.511999130249ms
7  -  10.689973831177ms
8  -  20.890951156616ms
9  -  41.686058044434ms
10  -  84.12504196167ms (default)
11  -  168.97416114807ms
12  -  334.79714393616ms
13  -  680.88603019714ms
14  -  1342.1139717102ms
15  -  2706.4559459686ms
16  -  5404.2019844055ms
17  -  10615.604162216ms

For an average site the default of 10 is probably a sane enough value.
To Top