编程语言
首页 > 编程语言> > php – 如何使用带有password_hash的Argon2算法?

php – 如何使用带有password_hash的Argon2算法?

作者:互联网

所以我听说PHP 7.2引入了新的Argon2 algorithm.但是我对如何将它与现有代码一起使用感到困惑.例如,我有这个

$password = password_hash('somepassword', PASSWORD_DEFAULT, ['cost' => 12]);

PASSWORD_DEFAULT现在使用Argon2吗?如果有的话,我需要使用password_verify进行更改? bcrypt现在被认为是不安全的吗?

解决方法:

什么是Argon2? bcrypt现在不好吗?

在PHP 7.2之前,使用的唯一散列算法password_hash是bcrypt.在撰写本文时,bcrypt仍然被认为是一个强哈希,特别是与其前身md5和sha1(两者都是insecure because they are fast)相比. Argon2是simply a costlier algorithm to brute force

Argon2i uses data-independent memory access. It is slower because it makes more passes over the memory to protect from trade off attacks. It is highly recommended for password hashing and password-based key derivation.

Bcrypt仍然是密码的可接受哈希值.如果你不想要,则无需切换(截至7.2.0版本).此外,PASSWORD_DEFAULT应仅在下一个完整版本(7.3.0或更高版本)上更改(每个PHP Internals policy).如果您想确保仅继续使用bcrypt,则可以使用PASSWORD_BCRYPT.然而,这是不必要的,我们将在下面讨论.

你如何使用Argon2?

首先,我们将password_hash的第二个参数切换为其中一个常量

> PASSWORD_ARGON2I – PHP 7.2.0
> PASSWORD_ARGON2ID – PHP 7.3.0(如果可用,请参见下面的注释)

然后我们需要改变我们的选择. bcrypt使用cost作为迭代密码次数的参数(更高的成本=更长的散列时间).然而,有不同的成本因素

password_hash('somepassword', PASSWORD_ARGON2I, ['memory_cost' => 2048, 'time_cost' => 4, 'threads' => 3]);

From the manual我们看到这些选项的作用

> memory_cost – 可用于计算Argon2散列的最大内存(以字节为单位)(默认为1024)
> time_cost – 计算Argon2哈希值所需的最长时间(默认值为2)
> threads – 用于计算Argon2哈希的线程数(默认值为2)

在更改这些内容之前,了解更高的成本会降低脚本速度.您需要在服务器上运行测试,以找到最适合您的设置.这通常是通过循环给定成本的几次迭代. PHP manual gives an example of this如果你需要一个.

另请注意,虽然bcrypt存储了60个字符,但Argon2可能需要更多.理想情况下,您应该使您的密码字段存储255个字符.

我们在password_verify中有什么变化?

这里的答案是……什么都没有.了解password_verify足够聪明,可以找出使用的算法并对其进行适当处理.如上所述,这意味着如果您使用的是PASSWORD_DEFAULT,则默认值可以更改而不会对您产生负面影响(尽管您可能需要调整成本参数). password_verify只需要它支持的算法.如果从bcrypt切换到Argon2,两者都将以相同的方式验证,因为为您存储了所有必需的数据(salt,hash和cost).

//Works for both bcrypt and Argon2
if(password_verify($user_password, $stored_hash)) {
    // password validated
}

如果要从bcrypt升级哈希值,可以在用户成功登录时执行此操作(从而为您提供未经过散列处理的密码).只需检查您的哈希是否以$2y $(bcrypt标记)开头.如果是,请将提供的密码再次传递给password_hash,但使用Argon2参数,并将其保存到登录用户的密码字段中.

什么是Argon2ID?

Introduced in PHP 7.3,如本Crypto.SE question所述,Argon2ID对Argon2I进行了一些改进

The best tradeoff attack on 1-pass Argon2id is the combined low-storage attack (for the first half of the memory) and the ranking attack (for the second half), which bring together the factor of about 2.1.

Argon2ID使用与Argon2I相同的参数.

标签:php-password-hash,php-7-2,php,algorithm,argon2-ffi
来源: https://codeday.me/bug/20191004/1851755.html