【发布时间】:2017-02-21 14:59:44
【问题描述】:
我知道一个与此 (How do I encrypt in Python and decrypt in Java?) 非常相似的问题,但我有一个不同的问题。
我的问题是,我无法在 Java 中正确解密。尽管使用了正确的密钥和 IV,但解密后我仍然会得到垃圾字符。我在 Java 中没有任何编译/运行时错误或异常,所以我相信我使用了正确的参数进行解密。
Python 加密代码 -
from Crypto.Cipher import AES
import base64
key = '0123456789012345'
iv = 'RandomInitVector'
raw = 'samplePlainText'
cipher = AES.new(key,AES.MODE_CFB,iv)
encrypted = base64.b64encode(iv + cipher.encrypt(raw))
Java 解密代码 -
private static String KEY = "0123456789012345";
public static String decrypt(String encrypted_encoded_string) throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
String plain_text = "";
try{
byte[] encrypted_decoded_bytes = Base64.getDecoder().decode(encrypted_encoded_string);
String encrypted_decoded_string = new String(encrypted_decoded_bytes);
String iv_string = encrypted_decoded_string.substring(0,16); //IV is retrieved correctly.
IvParameterSpec iv = new IvParameterSpec(iv_string.getBytes());
SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
plain_text = new String(cipher.doFinal(encrypted_decoded_bytes));//Returns garbage characters
return plain_text;
} catch (Exception e) {
System.err.println("Caught Exception: " + e.getMessage());
}
return plain_text;
}
我有什么明显的遗漏吗?
【问题讨论】:
-
@Pavneet Singh 您能否详细说明原因?
-
哦,我以为你发现了一些编译时错误或代码中的什么东西,让我收回我的标志
-
@PavneetSingh 没问题。我应该很清楚。我刚刚更新了问题,指出我没有任何编译时或运行时异常。
-
你能用垃圾打印java输出吗?
标签: java python encryption pycrypto cfb-mode