Blowfish的java和Python实现产生了不同的结果



我在java中有一个blowfish的遗留实现,我正试图将其移植到Python。

Java:

import blowfishj.*;
import org.apache.commons.codec.binary.Hex;
private static byte[] EncryptBlowFish(byte[] sStr, String sSecret) {        
    byte[] key = sSecret.getBytes();
    byte[] cipher = new byte[sStr.length];
    BlowfishECB blowfish = new BlowfishECB(key, 0, key.length);
    blowfish.encrypt(sStr, 0, cipher, 0, sStr.length);
    return (new String(Hex.encodeHex(cipher)));
}

Python:

from Crypto.Cipher import Blowfish
import binascii
def encrypt(encr_str, key_str):
    cipher = Blowfish.new(key_str, Blowfish.MODE_ECB)
    return binascii.hexlify(cipher.encrypt(encr_str)).decode('utf-8')

如果要加密的字符串是"12345678",密钥是"1234567490123456",则java代码输出"e00723bb58234aa",python代码输出"61d2570dc6e09632"。

由于java代码是遗留的,我不能碰它。这表明pycrypto的blowfish实现存在问题。然而,我可以确认这里接受的答案是有效的。但不知道为什么。我尝试了pycrypto和这个blowfish模块,得到了相同的结果。

有什么想法可以在Python中复制与遗留java代码相同的blowfish输出吗?

所有的功劳都归功于@Kai Iskratsch,因为他指向了正确的方向。

参考:

  1. 什么';Blowfish和Blowfish的同胞有什么区别?

  2. https://gist.github.com/adamb70/1f140573b37939e78eb5%22

这是对我有效的代码。

Python:

from Crypto.Cipher import Blowfish
from binascii import hexlify
def encrypt(key, string):
    """
    Encrypts input string using BlowFish-Compat ECB algorithm.
    :param key: secret key
    :param string: string to encrypt
    :return: encrypted string
    """
    cipher = Blowfish.new(key, Blowfish.MODE_ECB)
    return hexlify(_reverse_bytes(cipher.encrypt(_reverse_bytes(string)))).decode('utf-8')
@staticmethod
def _reverse_bytes(data):
    """
    Takes data and reverses byte order to fit blowfish-compat format. For example, using _reverse_bytes('12345678')
    will return 43218765.
    :param data as bytes
    :return: reversed bytes
    """
    data_size = 0
    for n in data:
        data_size += 1
    reversed_bytes = bytearray()
    i = 0
    for x in range(0, data_size // 4):
        a = (data[i:i + 4])
        i += 4
        z = 0
        n0 = a[z]
        n1 = a[z + 1]
        n2 = a[z + 2]
        n3 = a[z + 3]
        reversed_bytes.append(n3)
        reversed_bytes.append(n2)
        reversed_bytes.append(n1)
        reversed_bytes.append(n0)
    return bytes(reversed_bytes)

相关内容

  • 没有找到相关文章

最新更新