【发布时间】:2016-07-12 23:37:15
【问题描述】:
我已经尝试了多种方法来做到这一点,现在已经三天了,也有好几个小时。我已经无处可去。我正在使用 Java 使用 AES/CBC/PKCS7Padding 加密某些数据,并尝试在 Python 中使用相同的数据进行解密,但它不起作用。我正在使用这个 Python aes.py 库http://anh.cs.luc.edu/331/code/aes.py
我收到此错误:
File "/root/ascend/aes.py", line 384, in decrypt
block[(i+(j*4))] = iput[(i*4)+j]
exceptions.IndexError: list index out of range
这里是 Java Aes 代码:
public String aesEncrypt(String key, String data) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidAlgorithmParameterException {
SecretKey secKey = new SecretKeySpec(key.getBytes(), "AES");
KeyGenerator KeyGen = KeyGenerator.getInstance("AES");
KeyGen.init(256);
Cipher AesCipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
AesCipher.init(Cipher.ENCRYPT_MODE, secKey, new IvParameterSpec(IV.getBytes("UTF-8")));
byte[] byteCipherText = AesCipher.doFinal(data.getBytes());
return Base64.encodeToString(byteCipherText, 0).trim();
}
这里是 Java 密钥生成器,它也为 python 提供了使用的密钥:
public String genAESKey() {
String uuid = UUID.randomUUID().toString();
return uuid.replace("-","");
}
这是要解密的python代码:
self.data = aes.decryptData(user.aes_key, base64.b64decode(self.data))
#Where user.aes_key is the 256bit Aes key generated by java.
有人可以看看并解释这有什么问题吗?它们都使用相同的 aes 256 密钥、pkcs7 填充和 CBC。如果有人知道可以使用此类 java 代码的更好的库,请展示。
编辑:只是为了澄清一下,Aes 解密在 Java 中工作,而不是在 python 中,使用该 aes 密钥的 Python 加密工作,python 解密也是如此。只是不是java-> python。而self.data是java加密的aes数据。
编辑#2: 刚刚也尝试使用 PyCrypto 来做到这一点。发生了完全相同的错误。
return self._cipher.decrypt(ciphertext)
exceptions.ValueError: Input strings must be a multiple of 16 in length
【问题讨论】:
-
使用 PyCrypto:dlitz.net/software/pycrypto
-
您是否比较了两个程序的输出与相同的密钥和数据?一个人可能期待一个尾随空格或换行符,而另一个人没有。
标签: java python cryptography