为什么可以将bcrypt.hashpw同时用于哈希和验证密码? [英] Why can bcrypt.hashpw be used both for hashing and verifying passwords?
问题描述
在Python 2.7中使用 bcrypt
,我可以看到该示例使用bcrypt.hashpw
来都对存储的密码进行哈希处理,并验证给定的密码与经过哈希处理的密码匹配,如下所示:
Using bcrypt
with Python 2.7, I can see that the example uses the bcrypt.hashpw
to both hash a password for storage and verify that the given password matches a hashed one, like so:
import bcrypt
password = b"somepassword"
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
好的,到目前为止很好.现在,给定的密码使用bcrypt进行了哈希处理,因此它是一串哈希字节.
Ok, so far so good. The given password is now hashed using bcrypt, so it is a string of hashed bytes.
现在,这是令我感到困惑的部分:要检查纯文本密码是否与哈希密码匹配,请使用 same 函数,并使用哈希密码作为盐:
Now, here's the part that confuses me: to check that a plaintext password matches a hashed password, the same function is used, using the hashed password as a salt:
if bcrypt.hashpw(password, hashed) == hashed:
print("It Matches!")
else:
print("It Does not Match :(")
两个bcrypt.hashpw
调用的结果是否应该不同,因为输入盐不同?
Shouldn't the results of both bcrypt.hashpw
calls be different, since the input salts are different?
我能想到的唯一合理的答案是,在将盐添加到哈希密码之前,将其截断为固定长度.这样,在使用哈希结果时,仅保留生成的盐(在剥离尾随的哈希密码之后),并且使用截断后的盐对密码进行哈希的结果与原始盐相同.不过,我没有任何证据支持这一点.
The only reasonable answer I can think of is that the salt is truncated to a fixed length before being prepended to the hashed password. That way, when using the result of the hash, only the generated salt is left (after stripping off the trailing hashed password), and the result of hashing the password with the truncated salt is the same as the original. I don't have any evidence to support this, though.
为什么这样做?
推荐答案
在表达式bcrypt.hashpw(password, hashed)
中,仅hashed
的前几个字符用于表示盐,而不是整个字符串.
In the expression bcrypt.hashpw(password, hashed)
only the first couple of characters of hashed
are used for the salt, not the entire string.
例如,在此示例中,hashpw()
的输出如何以salt开头:
For instance, in this example how the output of hashpw()
begins with the salt:
salt1 = b"$2a$12$w40nlebw3XyoZ5Cqke14M."
print "salt1:", salt1
print "hash1:", bcrypt.hashpw(password, salt1)
打印:
salt1: $2a$12$w40nlebw3XyoZ5Cqke14M.
hash1: $2a$12$w40nlebw3XyoZ5Cqke14M.d.7cdO2wJhr/K6ZSDjODIxLrPmYzY/a
所以有一个约定,即盐只在第一个句点或前29个字符处出现.
so there is a convention where the salt only goes up the first period or the first 29 characters.
这篇关于为什么可以将bcrypt.hashpw同时用于哈希和验证密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!