PHP中的Django密码 [英] Django password in PHP
问题描述
我有一个问题,因为我有一个包含用户的数据库,而他们的密码已由Django(pbkdf2)保护.所以"123"看起来像这样:
I have a problem, because I have a database with users and theirs passwords were secured with Django (pbkdf2). So '123' looks like this:
pbkdf2_sha256$20000$MflWfLXbejfO$tNrjk42YE9ZXkg7IvXY5fikbC+H52Ipd2mf7m0azttk=
现在,我需要在PHP项目中使用此密码,而且我不知道如何比较它们.
Now I need to use this passwords in PHP project and I don't have any idea how to compare them.
推荐答案
pbkdf2_sha256$20000$MflWfLXbejfO$tNrjk42YE9ZXkg7IvXY5fikbC+H52Ipd2mf7m0azttk=
让我们分解一下. $
是分隔符:
Let's break this down. The $
are separators:
-
pbkdf2_sh256
表示PBKDF2-SHA256,即hash_pbkf2('sha256', ...)
-
20000
是迭代计数 -
MflWfLXbejfO
是盐 -
tNrjk42YE9ZXkg7IvXY5fikbC+H52Ipd2mf7m0azttk=
可能是哈希.
pbkdf2_sh256
means PBKDF2-SHA256, i.e.hash_pbkf2('sha256', ...)
20000
is the iteration countMflWfLXbejfO
is the salttNrjk42YE9ZXkg7IvXY5fikbC+H52Ipd2mf7m0azttk=
is likely the hash.
这是从PHP验证哈希所需的所有信息.您只需要:
This is all the information you need to validate the hash from PHP. You just need:
-
hash_pbkdf2()
从用户提供的密码中生成新的哈希 -
hash_equals()
将生成的哈希与存储的哈希进行比较
此功能应该可以使用(PHP 7 +):
This function should work (PHP 7+):
/**
* Verify a Django password (PBKDF2-SHA256)
*
* @ref http://stackoverflow.com/a/39311299/2224584
* @param string $password The password provided by the user
* @param string $djangoHash The hash stored in the Django app
* @return bool
* @throws Exception
*/
function django_password_verify(string $password, string $djangoHash): bool
{
$pieces = explode('$', $djangoHash);
if (count($pieces) !== 4) {
throw new Exception("Illegal hash format");
}
list($header, $iter, $salt, $hash) = $pieces;
// Get the hash algorithm used:
if (preg_match('#^pbkdf2_([a-z0-9A-Z]+)$#', $header, $m)) {
$algo = $m[1];
} else {
throw new Exception(sprintf("Bad header (%s)", $header));
}
if (!in_array($algo, hash_algos())) {
throw new Exception(sprintf("Illegal hash algorithm (%s)", $algo));
}
$calc = hash_pbkdf2(
$algo,
$password,
$salt,
(int) $iter,
32,
true
);
return hash_equals($calc, base64_decode($hash));
}
如果需要旧版PHP 5支持,则从函数定义中删除string
前缀和: bool
即可使其在PHP 5.6上运行.我不建议尝试为5.6之前的PHP版本添加向后兼容性.如果您发现自己处于这种情况,请您应该更新服务器软件.
If you need legacy PHP 5 support, removing the string
prefixes and the : bool
from the function definition will make it work on PHP 5.6. I don't advise trying to add backward compatibility for versions of PHP earlier than 5.6; if you find yourself in this situation, you should update your server software instead.
这篇关于PHP中的Django密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!