问题描述
我正在通过米格尔·格林伯格(Miguel Grinberg) 很棒的教程.在该章中,出于安全原因,他建议存储用户的密码哈希而不是密码本身.使用的功能是generate_password_hash
,check_password_hash
.但是,即使您使用相同的字符串调用generate_password_hash
,您也可以获得不同的哈希值:
>>> from werkzeug.security import generate_password_hash
>>> generate_password_hash('foo')
'pbkdf2:sha256:50000$E4Mg0BEy$c8db80b3ddefad78a93eaa47b22da5ce04adb969913b00545302cbf23501fdbb'
>>> generate_password_hash('foo')
'pbkdf2:sha256:50000$UCXVV09c$fe38b6099a0059957e283f2e4706fdbf01ef6e762b1070116df17867aa04e053'
然后,如果同一字符串可以具有任意多的哈希值,那么check_password_hash
如何工作?
密码会用salt散列,该salt是字母和数字的伪随机字符串.每次运行generate_password_hash()
时,盐值都会有所不同.因此,产生的散列也将不同.
这样做是为了使黑客无法简单地猜测常用密码的哈希值.例如,"pass1234"本身的哈希值每次都会相同.但是,"pass1234 + salt"的哈希值每次都不同.您的数据库应存储哈希值和盐值(重要的不是明文密码).这样可以最大程度地减少如果泄露有关用户帐户的信息所造成的损害.
对于Flask和werkzeug,generate_password_hash()
的返回值的格式为:method$salt$hash
(您可以在提供的屏幕快照中看到两个$
符号).因此,下次您针对哈希检查明文密码时,将其与generate_password_hash()
中的salt值一起使用,并查看其是否与哈希值匹配.
I am learning Flask through Miguel Grinberg's awesome tutorial. In that chapter, He suggests storing user's password hash rather than the password itself for security reasons. The functions been used are generate_password_hash
, check_password_hash
. But even if you call generate_password_hash
with the same string, you can get different hash values :
>>> from werkzeug.security import generate_password_hash
>>> generate_password_hash('foo')
'pbkdf2:sha256:50000$E4Mg0BEy$c8db80b3ddefad78a93eaa47b22da5ce04adb969913b00545302cbf23501fdbb'
>>> generate_password_hash('foo')
'pbkdf2:sha256:50000$UCXVV09c$fe38b6099a0059957e283f2e4706fdbf01ef6e762b1070116df17867aa04e053'
Then how does the check_password_hash
work if the same string can have as many hash values as it like?
Passwords are hashed with a salt, which is a pseudorandom string of letters and numbers. The salt will be different every time you run generate_password_hash()
. Therefore, the resulting hash will be different as well.
This is done so that hackers cannot simply guess the hash of common passwords. For example the hash of 'pass1234' by itself would be the same every time. However, the hash of 'pass1234 + salt will be different each time. Your database should store the hash, as well as the salt (importantly not the plaintext password). This minimises the damage caused if information is leaked about user accounts.
In the case of Flask and werkzeug, the return value of generate_password_hash()
is in the form: method$salt$hash
(you can see the two $
symbols in the screenshot you provided). So next time you check the plaintext password against the hash, you has it with the salt value from generate_password_hash()
and see if it matches the hash value.
这篇关于如何使用哈希检查密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!