使用 hashlib 的更新方法时如何禁用连接?

How can I disable concatenation when using hashlib's update method?

我已经使用 hashlib 编写了一种散列密码的方法。 我允许用户通过 POST 方法发送密码,该方法由 Flask 接收,随后对密码进行哈希处理,以便可以根据存储的 var 检查哈希是否相同。

无论是第一次发送正确的密码还是错误的密码,它都非常有效。 但是,如果用户在第一个 POST 发送了错误的密码,然后用正确的密码再次尝试,则会失败。 (如果第一次尝试成功并且用户继续尝试,也可以认为它失败了,但我现在不关心这个。)

I was able to narrow the problem down to hashlibs update function

hash.update(arg) Update the hash object with the string arg. Repeated calls are equivalent to a single call with the concatenation of all the arguments: m.update(a); m.update(b) is equivalent to m.update(a+b).

我想知道如何在重复调用时禁用串联。 这是否是一个 hacky 解决方法并不重要。

这是我的代码,以防有用:

h = hashlib.sha256()
VALID_USERNAME = 'admin'
VALID_PASSW_HASH = "210ce034be6d826a451a4261d70494148c5d7101627335ccacf8e00a711bcc5d"

@app.route('/api/queue/auth', methods=['POST'])
def auth():
    username = request.json.get('username')
    password = request.json.get('password')
    if bool(username) is False or bool(password) is False:
        return "\nPlease fill in both fields.\n", 400
    passwordBytes = password.encode(encoding='UTF-8',errors='strict')
    h.update(passwordBytes)
    if h.hexdigest() != VALID_PASSW_HASH or username != VALID_USERNAME:
        return "\nPlease check your username and password, and try again.\n", 401
    r.set('auth', 'true')
    return "Access Granted.\n", 200

补充说明:

只需将第一行从全局范围移到 auth() 函数中:

VALID_USERNAME = 'admin'
VALID_PASSW_HASH = "210ce034be6d826a451a4261d70494148c5d7101627335ccacf8e00a711bcc5d"

@app.route('/api/queue/auth', methods=['POST'])
def auth():
    username = request.json.get('username')
    password = request.json.get('password')
    if bool(username) is False or bool(password) is False:
        return "\nPlease fill in both fields.\n", 400
    passwordBytes = password.encode(encoding='UTF-8',errors='strict')
    h = hashlib.sha256()
    h.update(passwordBytes)
    if h.hexdigest() != VALID_PASSW_HASH or username != VALID_USERNAME:
        return "\nPlease check your username and password, and try again.\n", 401
    r.set('auth', 'true')
    return "Access Granted.\n", 200

或者更好的是,将密码的散列重构为不同的函数:

VALID_USERNAME = 'admin'
VALID_PASSW_HASH = "210ce034be6d826a451a4261d70494148c5d7101627335ccacf8e00a711bcc5d"

def hash_password(password):
    passwordBytes = password.encode(encoding='UTF-8',errors='strict')
    h = hashlib.sha256()
    h.update(passwordBytes)
    return h.hexdigest()


@app.route('/api/queue/auth', methods=['POST'])
def auth():
    username = request.json.get('username')
    password = request.json.get('password')
    if bool(username) is False or bool(password) is False:
        return "\nPlease fill in both fields.\n", 400
    if hash_password(password) != VALID_PASSW_HASH or username != VALID_USERNAME:
        return "\nPlease check your username and password, and try again.\n", 401
    r.set('auth', 'true')
    return "Access Granted.\n", 200