You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3调用bcrypt.hashpw报Invalid salt无效盐错误怎么解决

报错原因

bcrypt.hashpw()对传入的salt有严格格式要求,你传入的普通字符串编码后不符合bcrypt salt规范,因此抛出ValueError: Invalid salt错误:

  • 合法的bcrypt salt固定为$版本$cost值$22位base64编码字符的格式,总长度29字节
  • 版本一般为2a/2b,cost值为4-31之间的整数,后续22位是经过bcrypt自定义base64编码的盐值
解决方案

根据你的使用场景选择对应方案:

场景1:生成新的bcrypt哈希

直接用bcrypt自带的gensalt()方法生成符合规范的salt,无需手动构造:

import bcrypt

# 自动生成合法salt,可传入rounds参数指定迭代成本,默认值为12
salt = bcrypt.gensalt()

dictionary = open("dictionary.txt","r", encoding="utf-8")
for line in dictionary:
    testString = line.strip().encode('utf-8')
    h2 = bcrypt.hashpw(testString, salt)
    print(h2)

场景2:校验已有的bcrypt哈希

bcrypt生成的哈希值本身就包含了salt信息,直接将完整的存储哈希值作为salt参数传入即可,无需单独提取salt:

import bcrypt

# 替换为你存储的bcrypt哈希值(注意是bytes类型)
stored_hash = b"$2b$12$EixZaY3s7vjRjMRC/.R6/.tG8g5eH1yX7vjRjMRC/.R6/.tG8g5eH1yX"

dictionary = open("dictionary.txt","r", encoding="utf-8")
for line in dictionary:
    testString = line.strip().encode('utf-8')
    if bcrypt.hashpw(testString, stored_hash) == stored_hash:
        print(f"匹配成功:{line.strip()}")
        break

场景3:你需要使用指定字符串作为salt

如果必须用你提供的s = "5UA@/Mw^%He]SBaU"作为salt原始值,需要先将其处理为符合bcrypt规范的格式:

import bcrypt
import base64

raw_salt = "5UA@/Mw^%He]SBaU".encode('utf-8')
# 处理为bcrypt要求的22位自定义base64格式
processed_salt = base64.b64encode(raw_salt).decode('utf-8').replace('+', '.').rstrip('=')[:22].ljust(22, 'A')
# 拼接为完整salt格式,版本用2b,cost值设置为12(可自行调整)
valid_salt = f"$2b$12${processed_salt}".encode('utf-8')

dictionary = open("dictionary.txt","r", encoding="utf-8")
for line in dictionary:
    testString = line.strip().encode('utf-8')
    h2 = bcrypt.hashpw(testString, valid_salt)
    print(h2)

特殊说明

你给出的变量h是64位十六进制字符串,属于SHA256哈希结果,不是bcrypt哈希。如果你的需求是碰撞这个SHA256值,不需要使用bcrypt库,改用hashlib即可:

import hashlib

target_hash = "3281e6de7fa3c6fd6d6c8098347aeb06bd35b0f74b96f173c7b2d28135e14d45"
dictionary = open("dictionary.txt","r", encoding="utf-8")
for line in dictionary:
    test_str = line.strip().encode('utf-8')
    current_hash = hashlib.sha256(test_str).hexdigest()
    if current_hash == target_hash:
        print(f"找到匹配字符串:{line.strip()}")
        break

内容的提问来源于stack exchange,提问作者01Cyber_cyber10

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 20:54:02