在python中加密pdf文件,在java中用aes\u gcm模式解密该pdf文件

ecfdbz9o  于 2021-07-08  发布在  Java
关注(0)|答案(0)|浏览(379)

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

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题