如何从字符串为bcrypt.hashp

2024-09-29 21:59:28 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,我读了这个问题,明白了不应该使用非随机盐,但是对于这个例子,我需要:How can I set salt for bcrypt.hashpw?

我的代码:

import bcrypt

password = "pass"

hashed = bcrypt.hashpw( password, "a0a4310f19")

print hashed

我得到错误:

^{pr2}$

如何将此字符串转换为可接受的salt类?谢谢您!在


Tags: 代码importforpasspasswordcan例子how
1条回答
网友
1楼 · 发布于 2024-09-29 21:59:28

我的理解是salt必须是一个128位的值(16个八位字节),用base-64(24个字符)编码。在

如果您想使用固定salt进行调试,我会生成一个带有gensalt()函数的salt,然后简单地打印出来并永久使用它,而不是尝试像a0a4310f19这样的任意值。在

如果出于某种原因,您需要在问题中使用salt,那么您可能需要将salt扩展到128位,而不是当前的40位(假设它们实际上是字符串中的十六进制值,每个字符4位)。在

然后base64对其进行编码,在前面添加salt头。在

因此,将0000000000000000000000a0a4310f19注入base64编码器here得到{}。然后您可以在其前面加上salt头,以获得:

$2a$12$AAAAAAAAAAAAAACgpDEPGQ==

而且效果很好:

^{pr2}$

您甚至可以使用Python本身将10个字符的字符串转换为base64编码的salt,而不是依赖外部站点:

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:]))

相关问题 更多 >

    热门问题