首先,我阅读了这个问题并了解到不应使用非随机盐,但对于这种情况,我需要:How can I set salt for bcrypt.hashpw?
我的代码:
import bcrypt
password = "pass"
hashed = bcrypt.hashpw( password, "a0a4310f19")
print hashed
我得到错误:
ValueError: Invalid salt
如何将此字符串转换为可接受的盐类?谢谢!
最佳答案
我的理解是盐必须是一个 128 位值(16 个八位字节),用 base-64(24 个字符)编码。
如果你想使用固定盐进行(比如说)调试,我会用 gensalt()
函数生成一个,然后简单地打印出来并永远使用它,而不是尝试一些任意值,例如 a0a4310f19
。
如果出于某种原因,您需要在您的问题中使用该盐,您可能需要将其扩展到 128 位而不是您当前拥有的 40 位(假设它们实际上是该字符串中的十六进制值,每个字符四位)。
然后对其进行base64编码,在前面加上salt header。
因此,将 0000000000000000000000a0a4310f19
泵入 base64 编码器 here给你 AAAAAAAAAAAAAAACgpDEPGQ==
。然后,您可以在其前面加上 salt header 以获取:
$2a$12$AAAAAAAAAAAAAACgpDEPGQ==
这很好用:
import bcrypt
# Show correct format for verification.
print "Example salt format: %s" % (bcrypt.gensalt())
# Hash with fixed pre-calculated salt.
salt = "$2a$12$AAAAAAAAAAAAAACgpDEPGQ=="
print "Fixed salt hashing: %s" % (bcrypt.hashpw("pass", salt))
您甚至可以使用 Python 本身将 10 个字符的字符串转换为 base64 编码的盐,而不是依赖外部站点:
import bcrypt
import binascii
import base64
# Pre-calculated salt.
fsalt = "$2a$12$AAAAAAAAAAAAAACgpDEPGQ=="
# Your salt value (hex digits).
salt = "a0a4310f19"
# Work out salt based on your value. Could be improved but
# leaving it like this in case you want to check out all
# the intermediate values.
csalt = "0" * 32 + salt # Prefix to >= 32 digits.
csalt = csalt[-32:] # Only use last 32 digits.
csalt = binascii.a2b_hex(csalt) # Convert hex digits to binary.
csalt = base64.b64encode(csalt) # Encode binary with base64.
csalt = "$2a$12$" + csalt # Prefix with salt header.
# Hash with both salts for comparison.
print "Fixed salt hashing: %s" % (bcrypt.hashpw("pass",fsalt))
print "Calcd salt hashing: %s" % (bcrypt.hashpw("pass",csalt))
如果你想要一个用于设置 csalt
的代码,你可以使用:
csalt = "$2a$12$" + base64.b64encode(binascii.a2b_hex(("0" * 32 + salt)[-32:]))
关于python - 如何从字符串中为 bcrypt.hashpw 创建一个非随机盐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24729610/