2016-09-22 77 views
2

我刚刚学习如何使用MySQL和Python进行开发时遵守this tutorialPBKDF2中的盐 - Python

这是我的理解,userpassword存储在数据库散列,盐是沿着未加密的方式存储的,以便我们可以抓住哈希密码和salt,并使用输入的密码salt重新哈希,然后比较二。

虽然在使用PBKDF2时(通过passlib.hash.sha256_crypt()函数),我无法设置自己的盐,只能使用它的大小。那么我如何使用相同的盐重新密码,以便我可以比较两者?

+0

['hashlib.pbkdf2_hmac()'](https://docs.python.org/3/library/hashlib.html#hashlib.pbkdf2_hmac)需要盐。你使用什么功能? –

+0

即时通讯使用pbkdf2_sha256.encrypt,遵循http://www.cyberciti.biz/python-tutorials/securely-hash-passwords-in-python/ – hiperbolt

+0

中的指南[执行](https://pythonhosted.org/passlib /lib/passlib.hash.pbkdf2_digest.html#passlib.hash.pbkdf2_sha256)也需要盐。未指定时,将为您生成一个。 –

回答

1

Passlib Password Hash interface要么让你设置盐大小salt值本身。从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.encrypt("password", rounds=200000, salt=b'spamhameggs') 
'$pbkdf2-sha256$200000$c3BhbWhhbWVnZ3M$WL9OLVcb3f7HqHeNT./kCJeunydLCi4JykzEuAdewcI' 

但是,请注意,盐是返回字符串的一部分。该字符串不仅包含结果散列,还包含算法,使用的回合数使用的盐,由$定界。盐是encoded to modified form of base64。您可以通过串c3BhbWhhbWVnZ3M再次解码验证这一::

>>> from passlib.utils import ab64_decode 
>>> ab64_decode(b'c3BhbWhhbWVnZ3M') 
b'spamhameggs' 

请参阅pbkdf2_sha256文档的Format & Algorithm部分。

所以,当你存储完整的串pbkdf2_sha256在数据库中,一切验证字符串是正确的,在价值,包括盐。离开生成随机盐最好留给该库,因为它会使用安全的方法来生成一个。

+0

感谢您编辑问题并回复。对不起,我没有编辑它,我没有时间:( – hiperbolt