PHP 8.4.6 Released!

sodium_crypto_pwhash_str

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_pwhash_strDevuelve un hash codificado en ASCII

Descripción

sodium_crypto_pwhash_str(#[\SensitiveParameter] string $password, int $opslimit, int $memlimit): string

Utiliza un algoritmo de hachéo intensivo en CPU y memoria con un sel generado aleatoriamente, y límites de memoria y CPU para generar un hash codificado en ASCII adecuado para el almacenamiento de contraseñas.

Parámetros

password

string; La contraseña para la cual se generará un hash.

opslimit

Representa una cantidad máxima de cálculos a realizar. Aumentar este número hará que la función requiera más ciclos de CPU para calcular una clave. Existen constantes disponibles para definir el límite de operaciones a valores apropiados según el uso previsto, en orden de fuerza: SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE, SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE y SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE.

memlimit

La cantidad máxima de RAM que la función utilizará, en bytes. Existen constantes para ayudar a elegir un valor apropiado, en orden de tamaño: SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE, SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE y SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE. Típicamente, estos valores deberían asociarse con los valores opslimit correspondientes.

Valores devueltos

Devuelve el hash de la contraseña.

Para producir el mismo hash de contraseña a partir de la misma contraseña, los mismos valores para opslimit y memlimit deben ser utilizados. Estos valores están integrados en el hash generado, por lo que todo lo necesario para verificar el hash está incluido. Esto permite a la función sodium_crypto_pwhash_str_verify() verificar el hash sin necesidad de almacenamiento separado para los otros parámetros.

Ejemplos

Ejemplo #1 Ejemplo de sodium_crypto_pwhash_str()

<?php
$password
= 'password';
echo
sodium_crypto_pwhash_str(
$password,
SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE,
SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE
);

El resultado del ejemplo sería algo similar a:

$argon2id$v=19$m=65536,t=2,p=1$oWIfdaXwWwhVmovOBc2NAQ$EbsZ+JnZyyavkafS0hoc4HdaOB0ILWZESAZ7kVGa+Iw

Notas

Nota:

Los hashes son calculados utilizando el algoritmo Argon2ID, proporcionando resistencia tanto a ataques GPU como a ataques por canales laterales. A diferencia de la función password_hash(), no hay parámetro de sel (un sel es generado automáticamente), y los parámetros opslimit y memlimit no son opcionales.

Ver también

add a note

User Contributed Notes 1 note

up
4
marcus at synchromedia dot co dot uk
4 years ago
If you want to ensure that the hashes you generate with sodium_crypto_pwhash_str are compatible with those generated by password_hash, you need to keep an eye on that memory setting. According to the docs, the password_hash memory_cost param is given in "kibibytes", whereas sodium_crypto_pwhash_str uses bytes. I did some experiments to see what the difference is and ran into this:

echo password_hash('password',
PASSWORD_ARGON2ID,
[
'memory_cost' => 15000,
'time_cost' => 26,
'threads' => 1,
];

echo sodium_crypto_pwhash_str(
'password', 26,
15000000);

These result in:
$argon2id$v=19$m=15000,t=26,p=1$VG5MSkhUdEdFaGwyVG5sWA$laRHogIVAnC4ggLI8RdCDWlITTdicrdq0tK6SHGf4CI
$argon2id$v=19$m=14648,t=26,p=1$ClQ37/z9u7K6V1C2bkD4QA$51m8KhQQ9gujFSF+JyQR9d5QesayJiKsFmDU4HnGBHg

Notice that the "m=" numbers are different, and also different from what we asked for. It's down to the "kibibytes" unit. If we multiply the 15000 we used for password_hash by 1,024 instead of 1,000, we get 15,360,000, and using that number gives us the expected hash params:

echo sodium_crypto_pwhash_str(
'password', 26,
15360000);

$argon2id$v=19$m=15000,t=26,p=1$Qz3pWktOvT6X/LvdAk0bgQ$KosSFPfHUtWg+ppyRs3Op5/zIV6F6iy2Q7Gom8wP29c

This should be compatible with password_hash.

Incidentally the numbers I'm using for the Argon2id hash params are taken from the OWASP password guide, which recommend values different from PHP's default: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#argon2id
To Top