password_hash

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

password_hashCria um hash de senha

Descrição

password_hash(string $password, string|int|null $algo, array $options = []): string

password_hash() cria um novo hash de senha usando um algoritmo forte de hash de mão única.

Os seguintes algoritmos são suportados atualmente:

  • PASSWORD_DEFAULT - Usa o algoritmo bcrypt (padrão desde o PHP 5.5.0). Perceba que essa constante foi desenhada para mudar ao longo do tempo a medida que novos algoritmos mais fortes forem adicionados ao PHP. Por essa razão, o comprimento do resultado da utilização desse identificador pode mudar ao longo do tempo. Por isso, é recomendado que armazene o resultado em uma coluna do banco de dados que possa ser expandida além dos 60 caracteres (255 caracteres seria uma boa escolha).
  • PASSWORD_BCRYPT - Usa o algoritmo CRYPT_BLOWFISH para criar o hash. Produzirá um hash compatível com o padrão crypt() usando o identificador "$2y$". O resultado será sempre uma string de 60 caracteres, ou false em caso de falha.
  • PASSWORD_ARGON2I - Usa o algoritmo Argon2i para criar o hash. Este algoritmo somente estará disponível se o PHP tiver sido compilado com suporte a Argon2.
  • PASSWORD_ARGON2ID - Usa o algoritmo Argon2is para criar o hash. Este algoritmo somente estará disponível se o PHP tiver sido compilado com suporte a Argon2.

Opções suportadas por PASSWORD_BCRYPT:

  • salt (string) - para fornecer manualmente um salt a ser usado quando estiver sendo feito o hash da senha. Perceba que isso irá sobrepor e evitar que um salt seja gerado automaticamente.

    Se omitido, um salt aleatório será gerado pela função password_hash() para cada senha sofrendo hash. Esse é o modo de operação desejado.

    Aviso

    A opção salt está defasada. Agora é preferível que simplesmente se utilize o salt que é gerado por padrão. A partir do PHP 8.0.0, um salt fornecido explicitamente será ignorado.

  • cost (int) - indica o custo de algoritmo que deve ser usado. Exemplos desses valores podem ser encontrados na página da função crypt().

    Se omitido, um valor padrão 10 será usado. Este é um bom patamar de custo, mas pode-se considerar aumentar esse valor dependendo do hardware.

Opções suportadas por PASSWORD_ARGON2I e PASSWORD_ARGON2ID:

Parâmetros

password

A senha do usuário.

Cuidado

Usando PASSWORD_BCRYPT como algoritmo, resultará no parâmetro password sendo truncado em um comprimento máximo de 72 bytes.

algo

Uma constante de algoritmo de senha denotando o algoritmo a ser usado ao fazer o hash da senha.

options

Um array associativo contendo opções. Consulte as constantes de algoritmo de senha para obter a documentação sobre as opções suportadas por cada algoritmo.

Se omitido, um salt aleatório será gerado e o custo padrão será usado.

Valor Retornado

Retorna o hash da senha.

O algoritmo, o custo e o salt utilizados são retornados como parte do hash. Dessa forma, toda informação necessária para verificar o hash é incluída nele. Isso permite que a função password_verify() verifique o hash sem precisar de um armazenamento separado para a informação do salt ou do algoritmo.

Registro de Alterações

Versão Descrição
8.0.0 password_hash() não mais retorna false em caso de falha, em vez disso uma exceção ValueError será lançada se o algoritmo de hash da senha não for válido, ou uma exceção Error se o cálculo do hash falhou por motivo desconhecido.
8.0.0 O parâmetros algo agora pode ser nulo.
7.4.0 O parâmetro algo agora espera uma string, mas ainda aceita ints para compatibilidade com versões anteriores.
7.4.0 A extensão sodium fornece uma implementação alternativa para senhas Argon2.
7.3.0 Suporte para senhas Argon2id usando PASSWORD_ARGON2ID foi adicionado.
7.2.0 Suporte para senhas Argon2i usando PASSWORD_ARGON2I foi adicionado.

Exemplos

Exemplo #1 Exemplo de password_hash()

<?php
/**
* O objetivo é calcular o hash da senha usando o algortimo PASSWORD_DEFAULT atual.
* Atualmente é BCRYPT, e resultará em uma string de 60 caracteres.
*
* Fique ciente que PASSWORD_DEFAULT pode mudar com o tempo, por isso deve-se
* preparar para permitir strings com mais de 60 caracteres (255 é um bom número)
*/
echo password_hash("rasmuslerdorf", PASSWORD_DEFAULT);
?>

O exemplo acima produzirá algo semelhante a:

$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a

Exemplo #2 Exemplo de configuração do custo de password_hash() manualmente

<?php
/**
* Neste caso, o objetivo é aumentar o custo padrão de BCRYPT para 12.
* Note que agora o algortimo foi trocado para PASSWORD_BCRYPT, que sempre terá 60 caracteres.
*/
$options = [
'cost' => 12,
];
echo
password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);
?>

O exemplo acima produzirá algo semelhante a:

$2y$12$QjSH496pcT5CEbzjD/vtVeH03tfHKFy36d4J0Ltp3lRtee9HDxY3K

Exemplo #3 Exemplo de busca de um bom custo para password_hash()

<?php
/**
* Este código irá verificar o desempenho do servidor para determinar o quanto pode-se aumentar
* o custo. O objetivo é aumentar o custo ao valor mais alto possível sem deixar o servidor muito
* lento. 10 é um bom ponto de partida, e um valor maior será bom se o servidor for
* rápido o suficiente. O código abaix mira em ≤ 350 milissegundos de tempo adicional,
* que é um atraso adequado para sistemas que lidam com logins interativos.
*/
$timeTarget = 0.350; // 350 milissegundos

$cost = 10;
do {
$cost++;
$start = microtime(true);
password_hash("test", PASSWORD_BCRYPT, ["cost" => $cost]);
$end = microtime(true);
} while ((
$end - $start) < $timeTarget);

echo
"Custo Apropriado Encontrado: " . $cost;
?>

O exemplo acima produzirá algo semelhante a:

Custo Apropriado Encontrado: 12

Exemplo #4 Exemplo de password_hash() usando Argon2i

<?php
echo 'Argon2i hash: ' . password_hash('rasmuslerdorf', PASSWORD_ARGON2I);
?>

O exemplo acima produzirá algo semelhante a:

Argon2i hash: $argon2i$v=19$m=1024,t=2,p=2$YzJBSzV4TUhkMzc3d3laeg$zqU/1IN0/AogfP4cmSJI1vc8lpXRW9/S0sYY2i2jHT0

Notas

Cuidado

É fortemente recomendado que não seja gerado um salt próprio para esta função. Ela criará um salt seguro automaticamente se um não for especificado.

Como apontado acima, fornecer a opção salt no PHP 7.0 gerará um erro deprecation warning. O suporte para fornecer um salt manualmente foi removido no PHP 8.0.

Nota:

É recomendado que você teste esta função sem seus servidores, e ajuste o parâmetro custo para que a execução da função leve menos do que 350 milissegundos em sistemas interativos. O script do exemplo acima ajudará a escolher um bom valor de custo para seu hardware.

Nota: Atualizações dos algoritmos suportados por esta função (ou alterações no algoritmo padrão) precisam seguir as seguintes regras:

  • Qualquer novo algoritmo precisa estar no core por pelo menos 1 versão completa do PHP antes de se tornar padrão. Assim se, por exemplo, um novo algoritmo for adicionado na versão 7.5.5, ela não seria elegível para padrão até a versão 7.7 (uma vez que a 7.6 seria a primeira versão completa). Mas se um algoritmo diferente for adicionado na versão 7.6.0, ela seria elegível para padrão na 7.7.0.
  • O padrão deve mudar apenas em uma versão completa (7.3.0, 8.0.8 etc.) e não em uma versão de revisão. A única exceção seria uma emergênca caso uma falha de segurança crítica fosse encontrada no padrão atual.

Veja Também

add a note add a note

User Contributed Notes 12 notes

up
166
martinstoeckli
11 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
74
phpnetcomment201908 at lucb1e dot com
4 years ago
Since 2017, NIST recommends using a secret input when hashing memorized secrets such as passwords. By mixing in a secret input (commonly called a "pepper"), one prevents an attacker from brute-forcing the password hashes altogether, even if they have the hash and salt. For example, an SQL injection typically affects only the database, not files on disk, so a pepper stored in a config file would still be out of reach for the attacker. A pepper must be randomly generated once and can be the same for all users. Many password leaks could have been made completely useless if site owners had done this.

Since there is no pepper parameter for password_hash (even though Argon2 has a "secret" parameter, PHP does not allow to set it), the correct way to mix in a pepper is to use hash_hmac(). The "add note" rules of php.net say I can't link external sites, so I can't back any of this up with a link to NIST, Wikipedia, posts from the security stackexchange site that explain the reasoning, or anything... You'll have to verify this manually. The code:

// config.conf
pepper=c1isvFdxMDdmjOlvxpecFw

<?php
// register.php
$pepper = getConfigVariable("pepper");
$pwd = $_POST['password'];
$pwd_peppered = hash_hmac("sha256", $pwd, $pepper);
$pwd_hashed = password_hash($pwd_peppered, PASSWORD_ARGON2ID);
add_user_to_database($username, $pwd_hashed);
?>

<?php
// login.php
$pepper = getConfigVariable("pepper");
$pwd = $_POST['password'];
$pwd_peppered = hash_hmac("sha256", $pwd, $pepper);
$pwd_hashed = get_pwd_from_db($username);
if (
password_verify($pwd_peppered, $pwd_hashed)) {
    echo
"Password matches.";
}
else {
    echo
"Password incorrect.";
}
?>

Note that this code contains a timing attack that leaks whether the username exists. But my note was over the length limit so I had to cut this paragraph out.

Also note that the pepper is useless if leaked or if it can be cracked. Consider how it might be exposed, for example different methods of passing it to a docker container. Against cracking, use a long randomly generated value (like in the example above), and change the pepper when you do a new install with a clean user database. Changing the pepper for an existing database is the same as changing other hashing parameters: you can either wrap the old value in a new one and layer the hashing (more complex), you compute the new password hash whenever someone logs in (leaving old users at risk, so this might be okay depending on what the reason is that you're upgrading).

Why does this work? Because an attacker does the following after stealing the database:

password_verify("a", $stolen_hash)
password_verify("b", $stolen_hash)
...
password_verify("z", $stolen_hash)
password_verify("aa", $stolen_hash)
etc.

(More realistically, they use a cracking dictionary, but in principle, the way to crack a password hash is by guessing. That's why we use special algorithms: they are slower, so each verify() operation will be slower, so they can try much fewer passwords per hour of cracking.)

Now what if you used that pepper? Now they need to do this:

password_verify(hmac_sha256("a", $secret), $stolen_hash)

Without that $secret (the pepper), they can't do this computation. They would have to do:

password_verify(hmac_sha256("a", "a"), $stolen_hash)
password_verify(hmac_sha256("a", "b"), $stolen_hash)
...
etc., until they found the correct pepper.

If your pepper contains 128 bits of entropy, and so long as hmac-sha256 remains secure (even MD5 is technically secure for use in hmac: only its collision resistance is broken, but of course nobody would use MD5 because more and more flaws are found), this would take more energy than the sun outputs. In other words, it's currently impossible to crack a pepper that strong, even given a known password and salt.
up
44
nicoSWD
10 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
34
Cloxy
10 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
18
Lyo Mi
8 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
14
martinstoeckli
11 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
10
Mike Robinson
9 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
0
ms1 at rdrecs dot com
4 years ago
Timing attacks simply put, are attacks that can calculate what characters of the password are due to speed of the execution.

More at...
https://paragonie.com/blog/2015/11/preventing-timing-attacks-on-string-comparison-with-double-hmac-strategy

I have added code to phpnetcomment201908 at lucb1e dot com's suggestion to make this possible "timing attack" more difficult using the code phpnetcomment201908 at lucb1e dot com posted.

$pph_strt = microtime(true);

//...
/*The code he posted for login.php*/
//...

$end = (microtime(true) - $pph_strt);

$wait = bcmul((1 - $end), 1000000);  // usleep(250000) 1/4 of a second

usleep ( $wait );

echo "<br>Execution time:".(microtime(true) - $pph_strt)."; ";

Note I suggest changing the wait time to suit your needs but make sure that it is more than than the highest execution time the script takes on your server.

Also, this is my workaround to obfuscate the execution time to nullify timing attacks. You can find an in-depth discussion and more from people far more equipped than I for cryptography at the link I posted. I do not believe this was there but there are others. It is where I found out what timing attacks were as I am new to this but would like solid security.
up
-2
Anonymous
3 years ago
To use argon, follow these steps:

```
git clone https://github.com/p-h-c/phc-winner-argon2
cd phc-winner-argon2 && make && make install
apt install libsodium-dev
cd ~/php-7.4.5 // Your php installation source code
./configure [YOUR_EXISTING_CONFIGURE_COMMANDS] --with-password-argon2 --with-sodium
```
up
-6
Anonymous
4 years ago
According to the draft specification, Argon2di is the recommended mode of operation:

> 9.4.  Recommendations
>
>   The Argon2id variant with t=1 and maximum available memory is
>   recommended as a default setting for all environments.  This setting
>   is secure against side-channel attacks and maximizes adversarial
>   costs on dedicated bruteforce hardware.

source: https://tools.ietf.org/html/draft-irtf-cfrg-argon2-06#section-9.4
up
-3
php dot net at marksim dot org
3 years ago
regarding the sentence "...database column that can expand beyond 60 characters (255 characters would be a good choice). "

Considering future hash length increase by factor *2 and considering databases to start counting with 1, a password length of 256 characters (not 255) would probably be the better choice :)
up
-13
hman
4 years ago
I believe a note should be added about the compatibility of crypt() and password_hash().

My tests showed that yes, password_verify can also take hashes generated by crypt - as well as those from password_hash. But vice versa this is not true...

You cannot put hashes generated by password_hash into crypt for comparing them themselves, when used as the salt for crypt, as was recommended years ago (compare user entry with user crypt(userentry,userentry). No big deal, but it means that password checking routines MUST immediately be rewritten to use password_hash...

You cannot start using password_hash for hash generation without also altering the password check routine!

So the word "compatible" should be, IMHO, ammended with a word of caution, hinting the reader, that compatibility here is a one-way street.
To Top