【问题标题】:How can I rewrite password hasher written on Lua with Python?如何用 Python 重写在 Lua 上编写的密码哈希?
【发布时间】:2019-09-02 03:23:51
【问题描述】:

我必须为我的 Django 应用程序重写密码哈希器,才能使用旧数据库(使用 Lua 编写的旧哈希器)。我编写了几乎完全相同的代码,但它返回另一个哈希值。

这是我的代码:

def encode(password, salt):

    first_pass = hashlib.sha512()
    salted = (password + salt).encode('utf-8')

    first_pass.update(salted)

    digest = first_pass.digest()

    for i in range(1, 5000):
        next_pass = hashlib.sha512()
        next_pass.update(digest + salted)
        digest = next_pass.digest()

    hash = base64.b64encode(digest).decode('utf-8').strip()
    return hash

这是 Lua 中的代码:

function M.password_to_hash(plain_password, salt)

    local resty_sha512 = require("resty.sha512")

    local salted = plain_password.."{"..salt.."}"
    local first_pass = resty_sha512:new()

    first_pass:update(salted)

    local digest = first_pass:final()

    for i = 1, 4999 do
        local next_pass = resty_sha512:new()
        next_pass:update(digest..salted)
        digest = next_pass:final()
    end

    return ngx.encode_base64(digest)
end

我需要这些片段返回相等的哈希值。

例子:

password = testdevel

salt = 9675zt3fmtc0kg0c08k4c8wosc0ss8s

Python 函数返回:

6UbnltvNR6Y+wnUe2pd7RW/XglSB0SczKr7bUFCmv5l58eXuV2j3b9aSsD4DBeG44M6eJhStYE1sQIa95XbzlQ==

Lua 函数返回:

d5/dFCOfKDppXs5EYe3fGL+TF/0QN9myHTqXn0Ml8Xp7+bUOOTp2xuHjjm91mQNCxMJHiWleZtGRU86OqR5s9g==

【问题讨论】:

  • 请提供两个函数的一些示例输入和输出
  • 我对 lua 不是很熟悉,但看起来您的 lua 函数将 salted 设置为 <password>{<salt>},而您的 Python 函数将 salted 设置为 <password><salt>。您会期望这些生成不同的哈希值,因为您为哈希函数提供了不同的输入。
  • 你说得对,谢谢!

标签: python authentication encryption hash lua


【解决方案1】:

salted 在 python 中应该是:

salted = (password + '{' + salt + '}').encode('utf-8')

【讨论】:

  • 在 Lua 中你实际上是连接 salted 为:plain_password.."{"..salt.."}" 这基本上会给你"plain_password{salt}" 而在 Python 中你已经省略了这个括号,所以你基本上会有 "plain_passwordsalt",这个最终会得到完全不同的哈希值。
猜你喜欢
  • 2017-10-15
  • 1970-01-01
  • 2015-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 2019-11-29
相关资源
最近更新 更多