python编程密码检验_验证python passlib生成的密码哈希

I have a need to verify password hashes generated using python passlib. My objective is to use passlib's pbkdf2_sha512 scheme for hashing all user passwords. However, due to the nature of our backend, I need to verify this password from php scripts, js and java. I haven't found libraries in either of them that can take a passlib hash and verify the password. I was wondering if there exist one before I set out to implement passlib's hashing algorithm in php, js and java.

解决方案

I can offer this solution for php:

/*

* This function creates a passlib-compatible pbkdf2 hash result. Parameters are:

* $algo - one of the algorithms supported by the php `hash_pbkdf2()` function

* $password - the password to hash, `hash_pbkdf2()` format

* $salt - a random string in ascii format

* $iterations - the number of iterations to use

*/

function create_passlib_pbkdf2($algo, $password, $salt, $iterations)

{

$hash = hash_pbkdf2($algo, $password, base64_decode(str_replace(".", "+", $salt)), $iterations, 64, true);

return sprintf("\$pbkdf2-%s\$%d\$%s\$%s", $algo, $iterations, $salt, str_replace("+", ".", rtrim(base64_encode($hash), '=')));

}

I you copy the salt, iterations, and algorithm out of an existing passlib-generated hash string, and supply them with the plaintext password to this function, it will generated the same result as passlib.

Here's a php function to just verify a passlib pbkdf2 password, based on the above:

/*

* This function verifies a python passlib-format pbkdf2 hash against a password, returning true if they match

* only ascii format password are supported.

*/

function verify_passlib_pbkdf2($password, $passlib_hash)

{

if (empty($password) || empty($passlib_hash)) return false;

$parts = explode('$', $passlib_hash);

if (!array_key_exists(4, $parts)) return false;

/*

* Results in:

* Array

* (

* [0] =>

* [1] => pbkdf2-sha512

* [2] => 20000

* [3] => AGzdiek7yUzJ9iorZD6dBPdy

* [4] => 0298be2be9f2a84d2fcc56d8c88419f0819c3501e5434175cad3d8c44087866e7a42a3bd170a035108e18b1e296bb44f0a188f7862b3c005c5971b7b49df22ce

* )

*/

$t = explode('-', $parts[1]);

if (!array_key_exists(1, $t)) return false;

$algo = $t[1];

$iterations = (int) $parts[2];

$salt = $parts[3];

$orghash = $parts[4];

$hash = create_passlib_pbkdf2($algo, $password, $salt, $iterations);

return $passlib_hash === $hash;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值