Why can bcrypt.hashpw be used both for hashing and verifying passwords?

落花浮王杯 提交于 2019-12-04 07:47:12

In the expression bcrypt.hashpw(password, hashed) only the first couple of characters of hashed are used for the salt, not the entire string.

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)

prints:

salt1: $2a$12$w40nlebw3XyoZ5Cqke14M.
hash1: $2a$12$w40nlebw3XyoZ5Cqke14M.d.7cdO2wJhr/K6ZSDjODIxLrPmYzY/a

so there is a convention where the salt only goes up the first period or the first 29 characters.

The hashpw function returns the salted hash (iterated many times, following bcyrpt spec), preceeded by the salt used (and with a dot as seperator).

In : salt = bcrypt.gensalt()
In : all(salt == bcrypt.hashpw(pw,salt)[:len(salt)] for pw in ('','12345','asdfgh'))
Out: True

If the second argument to bcrypt.hashpw is recognized as of the form VALID_SALT.VALID_HASH, then the salt is automagically set to VALID_SALT, thus producing the same salt-hash-pair as the original password on identical pw input.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!