werkzeug.security generate_password_hash 没有 SHA-1 的替代方案

werkzeug.security generate_password_hash alternative without SHA-1

我使用 werkzeug.security 中的 generate_password_hash 来散列和加盐我的密码。我最近看到this article about SHA-1 collisionswerkzeug.security 使用 SHA-1,因为它不再那么安全,我想要一个替代方案。如何在不依赖 SHA-1 的情况下散列密码?

from werkzeug.security import generate_password_hash
generate_password_hash(secret)

generate_password_hash 中使用 SHA-1 并不容易受到攻击,因为它仅用作 PBKDF2 哈希中的中间迭代步骤。 See the discussion in chat.

when you're chaining zillions of hashes as in PBKDF2 the risk is indistinguishable from someone breaking a strong password by pure chance.

cryptography-dev 邮件列表上有进一步的讨论。

You're correct that HMAC's security is still fine when used with SHA-1, HMAC-MD5 is even secure believe it or not.


generate_password_hash 采用 method 参数来自定义哈希的生成方式。默认值为 pbkdf2:sha1。为PBKDF2传递不同的推导方式。

generate_password_hash(secret, method='pbkdf2:sha512')

您还可以将迭代次数从默认值 150,000 更改为更高的数字,但代价是散列速度较慢。 pbkdf2:sha1:200000.


您可能对 PBKDF2 没问题,只要哈希和迭代调整得很好。或者,使用 Passlib, which supports more hash methods than Werkzeug. See Passlib's recommended hashes 来讨论要使用的哈希值。此示例显示如何将 bcrypt 与 Passlib 结合使用。

pip install passlib bcrypt
from passlib.context import CryptContext
crypt_context = CryptContext(schemes=['bcrypt_sha256'])
crypt_context.hash(secret)