Hun*_*rco 4 python java encryption blowfish ecb
由于我对Java的不完全了解将这个加密代码转换为Python代码,我正在努力.两者应该具有完全相同的结果.非常感谢帮助.
Java函数
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
String s = "testings";
Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
Key key = new SecretKeySpec("6#26FRL$ZWD".getBytes(), "Blowfish");
cipher.init(1, key);
byte[] enc_bytes = cipher.doFinal(s.getBytes());
System.out.println(enc_bytes);
}
}
Run Code Online (Sandbox Code Playgroud)
Python等价
def PKCS5Padding(string):
byteNum = len(string)
packingLength = 8 - byteNum % 8
if packingLength == 8:
return string
else:
appendage = chr(packingLength) * packingLength
return string + appendage
def PandoraEncrypt(string):
from Crypto.Cipher import Blowfish
key = b'6#26FRL$ZWD'
c1 = Blowfish.new(key, Blowfish.MODE_ECB)
packedString = PKCS5Padding(string)
return c1.encrypt(packedString)
Run Code Online (Sandbox Code Playgroud)
结果
Java功能:"??¾ô"
Python功能:"Ë4A-¾`*ã"
我使用你的例子获得了python和Java的相同输出.
Java的:
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));
}
}
Run Code Online (Sandbox Code Playgroud)
蟒蛇:
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))
Run Code Online (Sandbox Code Playgroud)
在这两种情况下输出都是 223950ff19fbea872fce0ee543692ba7