How does PHP password_hash generate salt?
Hello, as you know, PHP has recently been introduced password_hash
, embedded in the latest versions. The documentation states:
If omitted, a random salt will be generated and the default value will be used.
The question is, what method does he use to add salt?
I'm wondering because I would like to know if the salt is created by accident so that when storing my hashed passwords, they are always unique .
source to share
The salt is randomly generated. They must be statistically unique.
To see how, the C source code ,
if (!buffer_valid) {
for (i = 0; i < raw_length; i++) {
buffer[i] ^= (char) (255.0 * php_rand(TSRMLS_C) / RAND_MAX);
}
}
Now, if C is not your cup of tea, the same logic and algorithms are implemented in PHP in:
$buffer = '';
$raw_length = (int) ($required_salt_len * 3 / 4 + 1);
$buffer_valid = false;
if (function_exists('mcrypt_create_iv')) {
$buffer = mcrypt_create_iv($raw_length, MCRYPT_DEV_URANDOM);
if ($buffer) {
$buffer_valid = true;
}
}
if (!$buffer_valid && function_exists('openssl_random_pseudo_bytes')) {
$buffer = openssl_random_pseudo_bytes($raw_length);
if ($buffer) {
$buffer_valid = true;
}
}
if (!$buffer_valid && is_readable('/dev/urandom')) {
$f = fopen('/dev/urandom', 'r');
$read = strlen($buffer);
while ($read < $raw_length) {
$buffer .= fread($f, $raw_length - $read);
$read = strlen($buffer);
}
fclose($f);
if ($read >= $raw_length) {
$buffer_valid = true;
}
}
if (!$buffer_valid || strlen($buffer) < $raw_length) {
$bl = strlen($buffer);
for ($i = 0; $i < $raw_length; $i++) {
if ($i < $bl) {
$buffer[$i] = $buffer[$i] ^ chr(mt_rand(0, 255));
} else {
$buffer .= chr(mt_rand(0, 255));
}
}
}
The only difference is which PHP version will use mcrypt
or openssl
if installed ...
source to share