【发布时间】:2017-07-31 03:19:15
【问题描述】:
我在 Java 中使用 AES 加密了一个字符串,并在 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)
我不明白为什么?填充?
【问题讨论】:
-
在 Java 中,您的 IV 是
0x00重复 16 次。在 Python 中,您的 IV 是0x30重复 16 次。显然,这些不一样。 -
嗨卢克:非常感谢!
-
不客气。最好不要自己手动填充。
标签: java python encryption aes