PHP:河豚算法给出 *0 作为输出

标签 php algorithm blowfish

我今天在研究 Blowfish 算法。一切正常,但有时我的程序会失败,因为 Blowfish Algo 将 *0 作为输出,因此之后的整个逻辑都会崩溃。

enter image description here

changelog 下的 CRYPT 的 PHP 官方文档页面上提到这个问题已经在版本 5.3.2 中解决

5.3.2    Fixed Blowfish behaviour on invalid rounds to return "failure" string ("*0" or "*1"), instead of falling back to DES.

我正在使用 PHP 5.5.9-1ubuntu4.2 并且仍然面临同样的问题。这是程序:

<?php
$password = 'Rajat';
$userpassword = 'Rajat';
echo $password;
echo "\n";
echo "Salt: ";
$salt = substr(uniqid(rand()),0,22);
echo $salt;
echo "\n";
echo "Using Blowfish: ";
$bf = crypt($password,'$2y$10$'.$salt);
echo $bf;
echo "\n";
echo "Starting password checking...\n";
$full_bf_salt = substr($bf,0,29);
$verify_hash = crypt($userpassword,$full_bf_salt);
echo "Verified calculated hash: ".$verify_hash;
if($verify_hash==$bf){
 echo "Password is correct\n";
}else{
 echo "Password is incorrect\n";
}
?>

大多数时候,crypt 函数按预期工作,但有时会失败。有谁知道为什么或者我以错误的方式实现了什么?

最佳答案

我设法用你的代码重现了这个错误。当生成的盐的长度小于 22 时,您会得到 *0。在我的例子中,长度是 21 个字符。

Salt: string(21) "6948531853de8c4cd7a85"
Using Blowfish: *0

Bcrypt 需要一个以 base64 格式编码的 128 位盐,从而产生 22 个字符的盐。当盐无效时,返回 *0 以指示出现错误。

这是使用 mcrypt_create_iv() 正确生成盐的一种方法:

$raw_salt_len = 16;
$required_salt_len = 22;

$salt = mcrypt_create_iv($raw_salt_len, MCRYPT_DEV_URANDOM);

$base64_digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
$bcrypt64_digits = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

$base64_string = base64_encode($salt);
$salt = strtr(rtrim($base64_string, '='), $base64_digits, $bcrypt64_digits);

if (function_exists('mb_substr')) {
    $salt = mb_substr($salt, 0, $required_salt_len, '8bit');
} else {
    $salt = substr($salt, 0, $required_salt_len);
}

我从 password_compat 库中提取了这段代码。我强烈建议研究它的代码。它涵盖了 mcrypt_create_iv() 不可用等情况。

关于PHP:河豚算法给出 *0 作为输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25104132/

相关文章:

PHP 安全 session

php - 为什么crontab不能按时执行

php - 隐藏 “Creating default object from empty value in”输出

PHP 对象到 JSON : How to create class that will have multiple recursive children?

arrays - 插入排序理论分析,总移位数。

algorithm - 逆时针排列凹多边形顶点

c++ - 将 SecByteBlock 中的 key 传递给算法?

php - Prestashop blocklayered + 无限滚动问题

algorithm - 有没有比 Bogosort(又名猴子排序)更糟糕的排序算法?

security - 破解 224 位 Blowfish 加密