Java中的pdf文件解密期间发生错误

时间:2020-11-05 13:22:56

标签: java encryption aes

我正在使用aes加密对pdf文件进行加密,它对文件进行了加密,没有任何错误,但是在解密pdf文件时却出现了一些参数丢失的错误。

我的代码用于加密和解密

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;

public class Encrypt {
    public static void main(String[] args) {
        try{

//            encryptWitEcb("src//d.pdf" , "src//d.enc.pdf" , "f1dda0fc3b96f6d0".getBytes());
            decryptWithEcb("src//d.enc.pdf" , "src//d.dec.pdf" ,"f1dda0fc3b96f6d0".getBytes());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void encryptWitEcb(String filenamePlain, String filenameEnc, byte[] key) throws Exception{
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        try (FileInputStream fis = new FileInputStream(filenamePlain);
             BufferedInputStream in = new BufferedInputStream(fis);
             FileOutputStream out = new FileOutputStream(filenameEnc);
             BufferedOutputStream bos = new BufferedOutputStream(out)) {
            byte[] ibuf = new byte[1024];
            int len;
            while ((len = in.read(ibuf)) != -1) {
                byte[] obuf = cipher.update(ibuf, 0, len);
                if (obuf != null)
                    bos.write(obuf);
            }
            byte[] obuf = cipher.doFinal();
            if (obuf != null)
                bos.write(obuf);
        }
    }

    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");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            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.security.InvalidKeyException: Parameters missing
    at com.sun.crypto.provider.CipherCore.init(CipherCore.java:469)
    at com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:313)
    at javax.crypto.Cipher.implInit(Cipher.java:805)
    at javax.crypto.Cipher.chooseProvider(Cipher.java:867)
    at javax.crypto.Cipher.init(Cipher.java:1252)
    at javax.crypto.Cipher.init(Cipher.java:1189)
    at Encrypt.decryptWithEcb(Encrypt.java:46)
    at Encrypt.main(Encrypt.java:11)

我该如何解决?

0 个答案:

没有答案