【发布时间】:2021-04-30 20:32:49
【问题描述】:
我有一些在 Java 中使用 AES 加密的数据。我现在想用 Python 解密。 这里参考的是解密 Java 代码:
public static String decryptAES(String input, String key) throws EncryptionException {
String clearText = null;
byte[] keyBytes = key.getBytes();
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
try {
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(1, keySpec);
// We need to revert our plus sign replacements from above
input = input.replaceAll(Pattern.quote("_"), "+");
byte[] decodedInput = Base64.decodeBase64(input.getBytes());
byte[] clearTextBytes = cipher.doFinal(decodedInput);
clearText = new String(clearTextBytes);
clearText = StringUtils.strip(clearText, "{");
} catch (Exception ex) {
throw new EncryptionException(ex);
}
return clearText;
}
这就是我所拥有的
from Crypto.Cipher import AES
encryptionKey = "]zOW=Rf*4*5F^R+?frd)G3#J%tH#qt_#"
encryptedData = "Hx8mA8afdgsngdfCgfdg1PHZsdfhIshfgdesd4rfgdk="
cipher = AES.new(encryptionKey.encode(), AES.MODE_ECB)
plain = cipher.decrypt(encryptedData.encode())
print(plain)
但我收到“ValueError:数据必须与 ECB 模式下的块边界对齐” 我做了谷歌,确实找到了一些建议,如ValueError: Data must be aligned to block boundary in ECB mode,但我无法真正让它发挥作用。不知道块大小应该是多少
【问题讨论】:
-
我可以玩这个,你期望什么未加密的价值?
-
Python 上没有 base64 解码?
-
cipher.init(1, keySpec)为 en 加密而不是 de 加密初始化cipher,因为1对应于Cipher.ENCRYPT_MODE。最好应用预定义的常量,这样就不会发生这样的事情,即用于解密Cipher.DECRYPT_MODE。但是,即使进行了此更改,您的数据也不会提供 UTF8 可解码的纯文本(如果应该这样的话)。
标签: python python-3.x cryptography