为什么crypt()使用相同的salt返回不同的哈希值?

时间:2012-08-17 14:10:55

标签: php encryption hash salt crypt

public static function blowfish($password, $storedpass = false) {
    //if encrypted data is passed, check it against input ($info) 
      if ($storedpass) { 
            if (substr($storedpass, 0, 60) == crypt($password, "$2a$08$".substr($storedpass, 60))) { 
                return true; 
            }  else { 
                return false; 
            } 
      }  else { 
            //make a salt and hash it with input, and add salt to end 
            $salt = "143cd669b02e155c3cca6e";//substr(bin2hex(openssl_random_pseudo_bytes(22)), 0, 22);
            //for ($i = 0; $i < 22; $i++) { 
                //$salt .= substr("./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", mt_rand(0, 63), 1); 
            //} 

            //return 82 char string (60 char hash & 22 char salt) 
            return crypt($password, "$2a$08$".$salt).$salt; 
     }
}

print(substr($storedpass, 0, 60)."<br />");
print(crypt($password, "$2a$08$".substr($storedpass, 60))."<br />");
print(substr($storedpass, 60));

产生结果:

$2a$08$143cd669b02e155c3cca6eM3k8s9BdE4jErJXJ8wSxshJDPcJQVPW
$2a$08$143cd669b02e155c3cca6eEiYm6ilW1ZC1PBS07LOh2XSq1NODSKK
143cd669b02e155c3cca6e

你可以看到我之前生成了22个字符的随机盐,我知道所有关于PHPASS,mt_rand()不是CSPRNG等等。混淆/担心我的原因就是为什么crypt()(给定$ password ='admin')即使使用静态salt也会生成不同的哈希值。你可以看到我打印了生成适当的salt的substr($ storedpass,60),但是然后运行crypt()函数(使用相同的参数来创建初始的$ storedpass)它会生成不同的结果,从而破坏身份验证我的应用程序(相对较小而非任务关键型)...

1 个答案:

答案 0 :(得分:1)

您似乎将$ password参数作为(undefined)发送给函数。

会生成此哈希:

$2a$08$143cd669b02e155c3cca6eM3k8s9BdE4jErJXJ8wSxshJDPcJQVPW

但是(例如)如果你运行它:

$password = 'admin';
echo $storedpass = blowfish($password)."<br />";

print(substr($storedpass, 0, 60)."<br />");
print(crypt('admin', '$2a$08$'.substr($storedpass, 60))."<br />");
print(substr($storedpass, 60));

if (blowfish($password, $storedpass) == true) {
    echo 1;
}

将输出:

$2a$08$143cd669b02e155c3cca6eEiYm6ilW1ZC1PBS07LOh2XSq1NODSKK143cd669b02e155c3cca6e
$2a$08$143cd669b02e155c3cca6eEiYm6ilW1ZC1PBS07LOh2XSq1NODSKK
$2a$08$143cd669b02e155c3cca6eEiYm6ilW1ZC1PBS07LOh2XSq1NODSKK
143cd669b02e155c3cca6e
1