使用python加密pdf文件,并使用AES_GCM模式在java中解密该pdf文件

2024-06-07 12:01:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题是,我无法用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)

Tags: comnewlenbsjavabyteoutcrypto

热门问题