在python中使用bcrypt进行哈希时,如何使用特定字符串作为salt并配置成本因子



我是bcrypt的新手,我正试图使用数据库上的特定字段来创建带有bcrypt功能的has。

到目前为止我做了什么

import bcrypt
# example password
password = "password123"
accountName = "james"
# converting password to array of bytes
pw_bytes = password.encode('utf-8')
# generating the salt
salt = (accountName.Upper()).encode()
# Hashing the password
pw_hash = bcrypt.hashpw(pw_bytes, salt)
print(pw_hash)

我收到这个错误消息

invalid salt

我也想加上成本因子4,但我不知道如何加。一些帮助会有一些好处。

正如bcrypt维基百科文章中所指出的,传递给bcrypt.hashpw的salt需要包含一个哈希算法标识符cost以及一个22字节的salt。

如果你想生成自己的盐,它可能看起来像:

from string import printable
import secrets
import bcrypt

def gen_salt(phrase: str, rounds: int = 12, prefix: bytes = b'2a') -> bytes:
# choose a random printable byte to use as pad character
pad_byte = secrets.choice(printable[:62]).encode()
padded_phrase = phrase.upper().encode().ljust(22, pad_byte)
cost = str(rounds).encode()
return b'$' + prefix + b'$' + cost + b'$' + padded_phrase

# example password
password = "password123"
accountName = "james"
# converting password to array of bytes
pw_bytes = password.encode('utf-8')
# generating the salt
salt = gen_salt(accountName)
print("salt:", salt)
# Hashing the password
pw_hash = bcrypt.hashpw(pw_bytes, salt)
print(pw_hash)

最新更新