2016-01-13 121 views
2

我有一個傳統的java的blowfish實現,我試圖移植到Python。Blowfish的Java和Python實現產生不同的結果

爪哇:

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」,並且鍵是 「123456789」,Java代碼輸出 「e00723bbb58234aa」 和蟒代碼輸出「61d2570dc6e09632」。

由於java代碼是遺留的,我無法觸及它。 This表示pycrypto實施河豚時存在問題。不過,我可以確認接受的答案here作品。不知道爲什麼。我嘗試了pycrypto以及this blowfish module,結果相同。

任何想法如何在Python中複製與傳統Java代碼相同的blowfish輸出?

+0

好像你的Java代碼使用河豚ECB模式,你檢查pyhon也在歐洲央行,而不是在CBC或其它模式下運行? –

+0

我正在使用'cipher = Blowfish.new(key_str,Blowfish.MODE_ECB)'。那不是把蟒蛇放到ECB模式嗎? –

+0

是的你的權利,經過一番嘲弄我自己,我認爲蟒蛇實際上產生河豚的正確結果。和java似乎是blowfish-compact –

回答

0

歸功於@Kai Iskratsch指向正確的方向。

參考:

  1. What's the difference between Blowfish and Blowfish-compat?

  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) 
相關問題