简体   繁体   English

如何使用 PHP 验证 htpasswd 生成的 bcrypt hash?

[英]How to verify a htpasswd-generated bcrypt hash using PHP?

I have to verify bcrypt-hashes created by apache's htpasswd tool (v2.4.41) using PHP's password_verify (v7.4.3).我必须使用 PHP 的password_verify (v7.4.3) 验证 apache 的htpasswd工具 (v2.4.41) 创建的 bcrypt-hashes。

But if I generate a hash:但如果我生成一个 hash:

$ htpasswd -nbB test pass
test:$2y$05$m73wHlBS62EUh7uAxbUCJ.gHIfcEgiorl/1LrzNRAlSSH4bmrBUEy

... and then try to verify it in PHP... ...然后尝试在 PHP 中验证它...

cat << EOF | php -a
if (password_verify('pass', '$2y$05$m73wHlBS62EUh7uAxbUCJ.gHIfcEgiorl/1LrzNRAlSSH4bmrBUEy')) {
  echo 'match';
} else {
  echo 'mismatch';
}
EOF

... mismatch is printed. ...打印mismatch PHP can however verify its own bcrypt hashes...然而,PHP 可以验证自己的 bcrypt 哈希...

cat << EOF | php -a
if (password_verify('test', password_hash('test', PASSWORD_BCRYPT))) {
  echo 'match';
} else {
  echo 'mismatch';
}
EOF

... this prints match . ...这打印match How can I get password_verify to verify the externally generated bcrypt hash?如何获取password_verify以验证外部生成的 bcrypt hash?

The problem was that in my real-world code there was additional whitespace at the end of the hash due incorrect parsing of the hash value out of a .htpasswd file.问题是,在我的实际代码中,由于对.htpasswd文件中的 hash 值的解析不正确,hash 末尾有额外的空格。

The 'simplified' example in the OP introduced another, different problem (due escaping special characters in the hash on the commandline) and failed because of that. OP 中的“简化”示例引入了另一个不同的问题(由于命令行上 hash 中的 escaping 特殊字符)并因此失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM