java - 在python中加密pdf文件并在java中使用AES_GCM模式解密该pdf文件
问题描述
我的问题是,我无法使用 aes gcm 模式正确解密 Java 中的 pdf 文件。尽管使用了正确的密钥和 IV,但我仍然在解密时出错。
Python 加密代码 -
def encrypt(in_file, out_file, password, key_length=32):
bs = AES.block_size
cipher = AES.new(password, AES.MODE_GCM, password )
finished = False
while not finished:
chunk = in_file.read(1024 * bs)
if len(chunk) == 0 or len(chunk) % bs != 0:
padding_length = (bs - len(chunk) % bs) or bs
# changed right side to str.encode(...)
chunk += str.encode(
padding_length * chr(padding_length))
finished = True
out_file.write(cipher.encrypt(chunk))
Java解密代码-
public static void decryptWithEcb(String filenameEnc, String filenameDec, byte[] key) throws Exception
{
try (FileInputStream in = new FileInputStream(filenameEnc);
FileOutputStream out = new FileOutputStream(filenameDec)) {
byte[] ibuf = new byte[1024];
int len;
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, key);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec ,gcmParameterSpec);
while ((len = in.read(ibuf)) != -1) {
byte[] obuf = cipher.update(ibuf, 0, len);
if (obuf != null)
out.write(obuf);
}
byte[] obuf = cipher.doFinal();
if (obuf != null)
out.write(obuf);
}
}
}
java中出现错误-
javax.crypto.AEADBadTagException: Tag mismatch!
at com.sun.crypto.provider.GaloisCounterMode.decryptFinal(GaloisCounterMode.java:620)
at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1116)
at com.sun.crypto.provider.CipherCore.fillOutputBuffer(CipherCore.java:1053)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:853)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
at javax.crypto.Cipher.doFinal(Cipher.java:2051)
at Encrypt.decryptWithEcb(Encrypt.java:72)
at Encrypt.main(Encrypt.java:15)
解决方案
推荐阅读
- java - 如何在复杂项目中包含属性文件
- php - 引导模式正在插入和更新数据库,问题是引导警报不起作用
- laravel - 尝试多个模型错误的问题
- http - queryParams 和 content-type 的区别:applciation/x-www-form-urlencoded
- shell - shell 命令中的“$it”是什么?
- html - 当您从建议下拉菜单中选择时,输入文本的颜色会发生变化
- node.js - 如何确认消息已发送到 RabbitMQ 队列?
- powerbi - 期间的 PowerBI 日期忽略过滤器/切片器度量
- data-science - 减小 Facebook 的 FastText Word2Vec 的大小
- c - 为什么我的程序没有为 C 中的循环(量子 = 4)调度模拟程序准确计算平均响应时间?