php - 在 PHP 5.5 中生成密码哈希并设置成本选项

标签 php passwords bcrypt php-password-hash

我知道 PHP 5.5 处于 alpha 阶段,但我制作的这个类只是提前制作的,目的是通过使用 function_exists() 来利用它的散列功能。

我检查了 password_hash文档。第三个参数是 $options,目前支持两个选项,'salt' 和 'cost'。

内容如下:

cost, which denotes the algorithmic cost that should be used. Examples of these values can be found on the crypt() page.

当我转到 crypt() 页面时,它提供的文档是:

Blowfish hashing with a salt as follows: "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 digits from the alphabet "./0-9A-Za-z". Using characters outside of this range in the salt will cause crypt() to return a zero-length string. The two digit cost parameter is the base-2 logarithm of the iteration count for the underlying Blowfish-based hashing algorithmeter and must be in range 04-31, values outside this range will cause crypt() to fail. Versions of PHP before 5.3.7 only support "$2a$" as the salt prefix: PHP 5.3.7 introduced the new prefixes to fix a security weakness in the Blowfish implementation. Please refer to » this document for full details of the security fix, but to summarise, developers targeting only PHP 5.3.7 and later should use "$2y$" in preference to "$2a$".

我似乎无法理解这个问题。它说 PHP 5.3.7 及更高版本应该使用 $2y$,但我使用什么成本值(value)来获得那个,它是最好的选择值(value)吗?他们提供的示例使用值 7,但根据上面的值可以达到 31,使用 say 4 与 say 31 有什么区别?

最佳答案

函数 password_hash() 只是函数 crypt() 的包装器,并且应该更容易正确使用它。它负责生成安全的随机盐,并提供良好的默认值。

使用此功能的最简单方法是:

$hash = password_hash($password, PASSWORD_DEFAULT);

这意味着,该函数将使用 BCrypt(算法 2y)对密码进行哈希处理,生成随机盐,并使用默认成本(目前为 10)。这些是很好的默认值,特别是我建议生成您自己的盐,那里很容易出错。

如果你想改变成本参数,你可以这样做:

$hash = password_hash($password, PASSWORD_BCRYPT, ["cost" => 11]);

成本参数增加 1,计算哈希值所需的时间加倍。成本参数是迭代次数的对数(以2为底),这意味着:

$iterations = 2 ^ $cost;

编辑:

我错过了要生成自己的类的要点。对于 PHP 5.3.7 及更高版本,存在一个 compatibility pack ,来自制作 password_hash() 函数的同一作者。您可以直接使用此代码,也可以查看精心设计的实现。对于 5.3.7 之前的 PHP 版本,不支持使用 2ycrypt,unicode 感知 BCrypt 算法。您可以改用 2a,这是早期 PHP 版本的最佳替代方案。我做了一个 example评论很多,也许你也想看看。

附言password_hash() 中正确使用了表达式“salt”和“cost factor”,但 crypt() 函数对所有 crypt 参数一起使用了 salt,这有点误导。

关于php - 在 PHP 5.5 中生成密码哈希并设置成本选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13905857/

相关文章:

php - 使用ajax的文件输入codeigniter

php - 尝试从数据库读取数据并将其显示在表中,其中 id 是插入 CodeIgniter 的最后一个 id

PHP如何检查一天是否是假期(在指定国家)?

php - 如何从数据库和 auth 用户中收回加盐密码?

PHP - 多个时差计算

swift - apple-app-site-association 文件是否适用于 GitHub Pages(即 site.github.io)?

c# - 连接到网络共享时如何提供用户名和密码

ruby-on-rails - Golang duplicate rails 设计 gem 密码加密

mysql - NSURLSession 密码安全

spring - 配置 Jasig CAS 以使用 BCrypt