python - 用 Python3 解密已经加密的数据
问题描述
我有一些用 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:数据必须与 ECB 模式下的块边界对齐,但我无法真正让它工作. 不知道块大小应该是多少
解决方案
@kelalaka 建议使用 Base64 解码解决了 Value 错误的问题,但输出似乎只是随机字节:
import base64
from Crypto.Cipher import AES
encryptionKey = "]zOW=Rf*4*5F^R+?frd)G3#J%tH#qt_#"
encryptedData = "Hx8mA8afdgsngdfCgfdg1PHZsdfhIshfgdesd4rfgdk="
data = base64.b64decode(encryptedData)
cipher = AES.new(encryptionKey.encode(), AES.MODE_ECB)
plain = cipher.decrypt(data)
print(plain)
输出:
b'\xcfh(\xb5\xec%(*^\xd4\xd3:\xde\xfb\xd9R<B\x8a\xb2+=\xbf\xc2%\xb0\x14h\x10\x14\xd3\xbb'
推荐阅读
- python - 通过 YouTube 数据 API 上传大视频时出现 Python MemoryError
- litedb - 通过 C# 进行简单的 LiteDB 查询(我在苦苦挣扎!)
- git - 为什么`git update-index`不会影响不在当前目录中的文件?
- azure-devops - Azure devops 抱怨语法循环
- sql-server - SSRS 报表界面加载时间长,仅在一个环境中
- python - InvalidArgumentError:断言失败:[无法将字节解码为 JPEG、PNG、GIF 或 BMP]
- html - 缩放网页超过 100% 会弄乱整个文本
- c - 调用函数时出现分段错误
- jenkins - Jenkins slave 作为 kubernetes pod
- javascript - 请指出我在学习异步 Javascript 时的误区