首页 > 解决方案 > 在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)

标签: javapythonencryptionaesaes-gcm

解决方案


推荐阅读