我使用AES在Java中加密了一个字符串,并在Python中解密。但是,在Python解密后,这里有随机字符,而不是预期的输出。
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;
public class AESCrypt{
public static final byte[] encBytes(byte[] srcBytes, byte[] key,
byte[] newIv) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
IvParameterSpec iv = new IvParameterSpec(newIv);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(srcBytes);
return encrypted;
}
public static final String encText(String sSrc)
throws Exception {
byte[] key =
{'a','r','e','y','o','u','o','k','a','r','e','y','o','u','o','k'};
byte[] ivk = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
byte[] srcBytes = sSrc.getBytes("utf-8");
byte[] encrypted = encBytes(srcBytes, key, ivk);
return Base64.encodeToString(encrypted,Base64.DEFAULT);
}
}
和python代码是:
#!/usr/bin/env python
from Crypto.Cipher import AES
import base64
key = 'areyouokareyouok'
iv = '0000000000000000'
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-ord(s[-1])]
def decrypt_aes(cryptedStr):
generator = AES.new(key, AES.MODE_CBC, iv)
cryptedStr = base64.b64decode(cryptedStr)
recovery = generator.decrypt(cryptedStr)
return unpad(recovery)
sourceStr = 'Dur/0RHadPwToNWczq8xk3mBdjybyw/yaMgas1F+WLg='
print decrypt_aes(sourceStr)
我不明白为什么?填充?
答案 0 :(得分:0)
我正在使用 Python >= 3.5
。可以通过以下方式使用 pycryptodome
解密您的 Java 加密数据:
#!/usr/bin/env python
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
key = 'areyouokareyouok'
_iv = "\x00"*AES.block_size # creates a 16 byte zero initialized string
def decrypt_aes(cryptedStr):
generator = AES.new(key.encode(), AES.MODE_CBC, _iv.encode())
cryptedStr_bytes = base64.b64decode(cryptedStr)
recovery = generator.decrypt(cryptedStr_bytes)
return unpad(recovery, AES.block_size)
sourceStr = 'Dur/0RHadPwToNWczq8xk3mBdjybyw/yaMgas1F+WLg='
print(f"Output - {decrypt_aes(sourceStr)}")
#Output - b'$PQWP6,014541.20,00000008*11\r\n'
我故意没有将最终解密的字节解码为字符串以显示原始字符串末尾有一个回车符和一个换行符。