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

Python中Blowfish加密与Blowfish.js输出不一致问题排查

问题:Blowfish加密结果不一致排查

使用Blowfish.js工具加密以下参数:

  • 待加密数据:ABCDEFGH
  • 密钥:Fd4595edcb6ddc10
  • 加密模式:CBC
  • 输出格式:base64

得到的加密结果为:tJ1xIcrzYzsk4YwjFccmbA==

但使用以下Python代码实现时,无法得到一致输出,请问遗漏了哪些环节?

from Crypto.Cipher import Blowfish
from Crypto.Util.Padding import pad
import base64
import os

def encrypt_data(data, key):
    # Ensure the data is a multiple of 8 bytes (64 bits)
    data = pad(data.encode(), 8)

    # Initialize the Blowfish cipher with the provided key
    cipher = Blowfish.new(key.encode(), Blowfish.MODE_CBC, os.urandom(8))

    # Encrypt the data
    ciphertext = cipher.encrypt(data)

    return base64.b64encode(ciphertext).decode()


if __name__ == "__main__":
    data_to_encrypt = 'ABCDEFGH'
    key = 'Fd4595edcb6ddc10'
    cipher_mode = "CBC"
    output_type = "base64"

    encrypted_data = encrypt_data(data_to_encrypt, key)
    print("Encrypted data:", encrypted_data)

问题原因及修正方案

你的代码和Blowfish.js工具的逻辑存在三处关键差异,导致结果不一致:

1. 初始化向量(IV)不匹配

Blowfish.js在CBC模式下默认使用全0字节的IV(即b'\x00\x00\x00\x00\x00\x00\x00\x00'),而你的代码通过os.urandom(8)生成随机IV。CBC模式下,IV必须完全相同才能生成一致的密文,随机IV每次都会导致结果不同。

2. 填充逻辑冗余

待加密数据ABCDEFGH的长度恰好是Blowfish的块大小(8字节),Blowfish.js不会对其进行填充;但你的代码调用pad(data.encode(), 8)使用PKCS7填充规则,会额外添加8个0x08字节,使得加密数据长度从8字节变为16字节,最终加密结果自然不同。

3. 结果拼接规则不同

Blowfish.js会将IV和密文拼接后再进行Base64编码,而你的代码仅对密文单独编码,缺少IV部分,这是结果长度和内容差异的核心原因。


修正后的Python代码

from Crypto.Cipher import Blowfish
import base64

def encrypt_data(data, key):
    # 使用全0字节的IV,和Blowfish.js保持一致
    iv = b'\x00' * 8
    # 数据刚好是块大小,无需填充
    data_bytes = data.encode()
    
    # 初始化Blowfish CBC加密器
    cipher = Blowfish.new(key.encode(), Blowfish.MODE_CBC, iv)
    ciphertext = cipher.encrypt(data_bytes)
    
    # 拼接IV和密文后再Base64编码
    return base64.b64encode(iv + ciphertext).decode()


if __name__ == "__main__":
    data_to_encrypt = 'ABCDEFGH'
    key = 'Fd4595edcb6ddc10'

    encrypted_data = encrypt_data(data_to_encrypt, key)
    print("Encrypted data:", encrypted_data)  # 输出:tJ1xIcrzYzsk4YwjFccmbA==

内容的提问来源于stack exchange,提问作者Chetan Kalewar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 00:43:21