Java Python河豚加密

Java Python河豚加密,java,python,encryption,blowfish,ecb,Java,Python,Encryption,Blowfish,Ecb,由于我对Java的不完全了解,我很难将此加密代码转换为Python代码。这两者的结果应该完全相同。非常感谢您的帮助 Java函数 Python等价物 结果 Java函数:“??” Python函数:“Ë4A-¾`*ã” 使用chr而不是str >>> chr(1) '\x01' >>> str(1) '1' str*int->重复str >>> '!' * 5 '!!!!!' 使用您的示例,我得到了python和Java的相同输出 爪哇:

由于我对Java的不完全了解,我很难将此加密代码转换为Python代码。这两者的结果应该完全相同。非常感谢您的帮助

Java函数

Python等价物

结果

Java函数:“??”

Python函数:“Ë4A-¾`*ã”

使用chr而不是str

>>> chr(1)
'\x01'
>>> str(1)
'1'
str*int->重复str

>>> '!' * 5
'!!!!!'

使用您的示例,我得到了python和Java的相同输出

爪哇:

Python:

from Crypto.Cipher import Blowfish
import binascii

# See @falsetru answer for the following method
#
def PKCS5Padding(string):
    byteNum = len(string)
    packingLength = 8 - byteNum % 8
    appendage = chr(packingLength) * packingLength
    return string + appendage

def PandoraEncrypt(string):
    key = b'6#26FRL$ZWD'
    c1  = Blowfish.new(key, Blowfish.MODE_ECB)
    packedString = PKCS5Padding(string)
    return c1.encrypt(packedString)

if __name__ == '__main__':
    s = 'testings'
    c = PandoraEncrypt(s)
    print(binascii.hexlify(c))

在这两种情况下,输出都是
223950ff19fbea872fce0ee543692ba7

我认为当
packingLength==8时,您的PKCS5Padding是错误的。谢谢,我已经做了适当的改变,这些输出是没有意义的。您可能应该打印十六进制编码的输出。在python中使用binascii.hexlify,在Java中并不是那么简单,但你会在网上找到很多例子。是的,但即使转换为十六进制,它们也不相等。我需要一个精确的副本供第三方扩展读取。第三方接收加密,因此它们必须相等。它是为Java设计的,但在我的项目中,Python更方便。@JoachimIsaksson,
packingLength
string
的长度是8的倍数时变为0。啊,我错过了你更改计算的机会。它实际上应该仍然是
packingLength=8-byteNum%8
,否则它将无法正确填充。例如,一个空字符串应该得到8个字节,值为8作为填充。感谢您的帮助,尽管程序无法工作。我已经用每个问题的样本结果更新了问题function@HunterLarco,尝试
System.out.write(enc_字节)而不是
。println
。是的,正如我一小时前发现的,当两者都转换为十六进制时,它们实际上是等效的,显然我对java不太了解,谢谢!
>>> chr(1)
'\x01'
>>> str(1)
'1'
>>> '!' * 5
'!!!!!'
import java.math.BigInteger;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class Blowfish1 {

    public static void main(String[] args) throws Exception {
        String s = "testings";
        Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
        Key key = new SecretKeySpec("6#26FRL$ZWD".getBytes(), "Blowfish");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] enc_bytes = cipher.doFinal(s.getBytes());
        System.out.printf("%x%n", new BigInteger(1, enc_bytes));
    }

}
from Crypto.Cipher import Blowfish
import binascii

# See @falsetru answer for the following method
#
def PKCS5Padding(string):
    byteNum = len(string)
    packingLength = 8 - byteNum % 8
    appendage = chr(packingLength) * packingLength
    return string + appendage

def PandoraEncrypt(string):
    key = b'6#26FRL$ZWD'
    c1  = Blowfish.new(key, Blowfish.MODE_ECB)
    packedString = PKCS5Padding(string)
    return c1.encrypt(packedString)

if __name__ == '__main__':
    s = 'testings'
    c = PandoraEncrypt(s)
    print(binascii.hexlify(c))