Prevent use of an invalid salt for Blowfish hashing of passwords

This commit is contained in:
Fedor A. Fetisov 2014-06-08 20:54:58 +04:00
parent f15ce27cde
commit fc25f35655

View File

@ -428,10 +428,10 @@ function calculate_password_hash($login, $password)
$hash = '*0'; $hash = '*0';
if (CRYPT_BLOWFISH == 1) { if (CRYPT_BLOWFISH == 1) {
if (defined('PHP_VERSION_ID') && (PHP_VERSION_ID > 50306)) { if (defined('PHP_VERSION_ID') && (PHP_VERSION_ID > 50306)) {
$hash = crypt($password, '$2y$08$' . $login); $hash = crypt($password, '$2y$08$' . generate_bf_salt($login));
} }
else { else {
$hash = crypt($password, '$2a$08$' . $login); $hash = crypt($password, '$2a$08$' . generate_bf_salt($login));
} }
} }
@ -452,4 +452,47 @@ function check_password_hash($login, $password, $hash)
} }
} }
function generate_bf_salt($string) {
$result = '';
$bin = unpack('C*', md5($string, TRUE));
for ($i=0; $i<count($bin); $i++) {
$shift = 2 + ($i % 3) * 2;
$first = ($bin[$i+1] >> $shift);
$second = ($bin[$i+1] & bindec(str_repeat('1', $shift)));
switch ($shift) {
case 2 :
$result .= bf_salt_character($first);
$tmp = $second;
break;
case 4 :
$result .= bf_salt_character(($tmp << 4) | $first);
$tmp = $second;
break;
case 6 :
$result .= bf_salt_character(($tmp << 2) | $first);
$result .= bf_salt_character($second);
break;
}
}
if ($shift == 2) {
$result .= bf_salt_character($second);
}
return $result;
}
function bf_salt_character($num) {
if ($num > 63) {
return chr(46);
}
elseif ($num < 12) {
return chr(46 + $num);
}
elseif ($num < 38) {
return chr(53 + $num);
}
else {
return chr(59 + $num);
}
}
?> ?>