小编典典

为什么werkzeugs`generate_password_hash`的输出不是恒定的?

flask

当我多次werkzeug.security.generate_password_hash("Same password")(docs)运行时,每次输出都不同。

我究竟做错了什么?为什么不是恒定的?


阅读 530

收藏
2020-04-06

共1个答案

小编典典

由于每次调用该函数时都会随机生成盐,因此生成的密码哈希也不同。返回的哈希值包含生成的盐,因此仍可以正确验证密码。

演示:

>>> from werkzeug.security import generate_password_hash
>>> generate_password_hash('foobar')
'pbkdf2:sha1:1000$tYqN0VeL$2ee2568465fa30c1e6680196f8bb9eb0d2ca072d'
>>> generate_password_hash('foobar')
'pbkdf2:sha1:1000$XHj5nlLU$bb9a81bc54e7d6e11d9ab212cd143e768ea6225d'

这两个字符串不同。但包含足够的信息来验证密码,因为生成的盐包含在每个密码中:

# pbkdf2:sha1:1000$tYqN0VeL$2ee2568465fa30c1e6680196f8bb9eb0d2ca072d
  ^^^^^^^^^^^^^^^^   salt   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      algo info    ^^^^^^^^        actual hash of the password
  (PBKDF2 applied SHA1 1000 times)

Because the random salt is tYqN0VeL for one and XHj5nlLU, the resulting hash is also different.

The foobar password can still be verified against either hash:

>>> from werkzeug.security import check_password_hash
>>> check_password_hash('pbkdf2:sha1:1000$tYqN0VeL$2ee2568465fa30c1e6680196f8bb9eb0d2ca072d', 'foobar')
True
>>> check_password_hash('pbkdf2:sha1:1000$XHj5nlLU$bb9a81bc54e7d6e11d9ab212cd143e768ea6225d', 'foobar')
True
2020-04-06