PBKDF2 中的盐 - Python
Salt in PBKDF2 - Python
我刚刚学习如何在使用 MySQL 和 Python 进行开发时保护密码,遵循 this tutorial。
据我了解,userpassword是存储在数据库中的hashed,salt是未加密存储的,这样我们就可以抓取hash后的密码和salt,再用salt对输入的密码进行hash,然后比较两人
不过,当使用 PBKDF2(通过 passlib.hash.sha256_crypt()
函数)时,我不能设置自己的盐,只能设置它的大小。那么我如何使用相同的盐重新散列密码以便我可以比较两者?
Passlib Password Hash interface either lets you set the salt size, or the salt
value itself. From the documentation on pbkdf2_sha256
:
salt
(bytes) Optional salt bytes. If specified, the length must be between 0-1024 bytes. If not specified, a 16 byte salt will be autogenerated (this is recommended).
salt_size
(int) – Optional number of bytes to use when autogenerating new salts. Defaults to 16 bytes, but can be any value between 0 and 1024.
所以你可以设置你自己的预生成盐:
>>> from passlib.hash import pbkdf2_sha256
>>> pbkdf2_sha256.hash("password", rounds=200000, salt=b'spamhameggs')
'$pbkdf2-sha2560000$c3BhbWhhbWVnZ3M$WL9OLVcb3f7HqHeNT./kCJeunydLCi4JykzEuAdewcI'
但是,请注意盐是返回字符串的一部分。该字符串不仅包含生成的哈希值,还包含算法、使用的轮数 和 使用的盐,由 $
分隔。盐是encoded to modified form of base64。您可以通过再次解码字符串 c3BhbWhhbWVnZ3M
来验证这一点::
>>> from passlib.utils.binary import ab64_decode
>>> ab64_decode(b'c3BhbWhhbWVnZ3M')
b'spamhameggs'
请参阅 pbkdf2_sha256
文档的 Format & Algorithm 部分。
因此,当您将完整的字符串 pbkdf2_sha256
存储在数据库中时,验证字符串 的所有内容都在值中,包括盐。生成随机盐最好留给该库,因为它将使用安全方法生成随机盐。
您可能需要阅读 Passlib tutorial on password hashing,其中包括如何在将密码存储在数据库中时对密码进行散列,以及如何再次验证它们(例如使用 pdkdf2_sha256.verify(password_user_entered, hash_stored_in_database)
),其中完全涵盖这个地.
我刚刚学习如何在使用 MySQL 和 Python 进行开发时保护密码,遵循 this tutorial。
据我了解,userpassword是存储在数据库中的hashed,salt是未加密存储的,这样我们就可以抓取hash后的密码和salt,再用salt对输入的密码进行hash,然后比较两人
不过,当使用 PBKDF2(通过 passlib.hash.sha256_crypt()
函数)时,我不能设置自己的盐,只能设置它的大小。那么我如何使用相同的盐重新散列密码以便我可以比较两者?
Passlib Password Hash interface either lets you set the salt size, or the salt
value itself. From the documentation on pbkdf2_sha256
:
salt
(bytes) Optional salt bytes. If specified, the length must be between 0-1024 bytes. If not specified, a 16 byte salt will be autogenerated (this is recommended).
salt_size
(int) – Optional number of bytes to use when autogenerating new salts. Defaults to 16 bytes, but can be any value between 0 and 1024.
所以你可以设置你自己的预生成盐:
>>> from passlib.hash import pbkdf2_sha256
>>> pbkdf2_sha256.hash("password", rounds=200000, salt=b'spamhameggs')
'$pbkdf2-sha2560000$c3BhbWhhbWVnZ3M$WL9OLVcb3f7HqHeNT./kCJeunydLCi4JykzEuAdewcI'
但是,请注意盐是返回字符串的一部分。该字符串不仅包含生成的哈希值,还包含算法、使用的轮数 和 使用的盐,由 $
分隔。盐是encoded to modified form of base64。您可以通过再次解码字符串 c3BhbWhhbWVnZ3M
来验证这一点::
>>> from passlib.utils.binary import ab64_decode
>>> ab64_decode(b'c3BhbWhhbWVnZ3M')
b'spamhameggs'
请参阅 pbkdf2_sha256
文档的 Format & Algorithm 部分。
因此,当您将完整的字符串 pbkdf2_sha256
存储在数据库中时,验证字符串 的所有内容都在值中,包括盐。生成随机盐最好留给该库,因为它将使用安全方法生成随机盐。
您可能需要阅读 Passlib tutorial on password hashing,其中包括如何在将密码存储在数据库中时对密码进行散列,以及如何再次验证它们(例如使用 pdkdf2_sha256.verify(password_user_entered, hash_stored_in_database)
),其中完全涵盖这个地.