本文介绍了验证python passlib生成的密码哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要验证使用python passlib 生成的密码哈希.我的目标是使用passlib的pbkdf2_sha512方案对所有用户密码进行哈希处理.但是,由于后端的性质,我需要从php脚本,js和java验证此密码.我在这两个库中都没有找到可以通过passlib哈希并验证密码的库.我想知道在开始使用php,js和java实现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.

推荐答案

我可以为php提供此解决方案:

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), '=')));
}

我将盐,迭代和算法从现有的passlib生成的哈希字符串中复制出来,并为该函数提供纯文本密码,它将产生与passlib相同的结果.

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.

基于上述内容,这是一个仅用于验证passlib pbkdf2密码的php函数:

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;
}

这篇关于验证python passlib生成的密码哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 18:09