我知道一个与此 (How do I encrypt in Python and decrypt in Java?) 非常相似的问题,但我有一个不同的问题。
我的问题是,我无法用 Java 正确解密。尽管使用了正确的 key 和 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;
}
有什么明显我遗漏的吗?
最佳答案
Cipher Feedback (CFB) mode of operation是模式族。它由段大小(或寄存器大小)参数化。 PyCrypto 默认有一个 segment size of 8 bit Java(实际上是 OpenJDK)的默认段大小为 same as the block size (AES 为 128 位)。
如果你想在 pycrypto 中使用 CFB-128,你可以使用 AES.new(key, AES.MODE_CFB, iv, segment_size=128)
。如果您想在 Java 中使用 CFB-8,可以使用 Cipher.getInstance("AES/CFB8/NoPadding");
。
既然我们已经解决了这个问题,您还有其他问题:
始终指定您正在使用的字符集,因为它可以在不同的 JVM 之间更改:
new String(someBytes, "UTF-8")
和someString.getBytes( “UTF-8”)
。当你这样做时,要保持一致。切勿使用字符串来存储二进制数据 (
new String(encrypted_decoded_bytes);
)。您可以直接复制字节:IvParameterSpec iv = new IvParameterSpec(Arrays.copyOf(encrypted_decoded_bytes, 16));
和cipher.doFinal(Arrays.copyOfRange(encrypted_decoded_bytes, 16, encrypted_decoded_bytes.length) )
。在 Java 中,您假设 IV 写在密文前面,然后一起编码,但在 Python 中,您永远不会对 IV 做任何事情。我猜你发布了不完整的代码。
如果 key 保持不变,则每次使用不同 IV 对 CFB 模式至关重要。如果您不为每次加密更改 IV,您将创建一个多次一密,使攻击者即使不知道 key 也能推断出明文。
关于java - 使用 AES-CFB 在 Python 中加密并在 Java 中解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40004858/