Java 使用AES-CBC-PKCS5Padding解密数据时出现填充错误

Java 使用AES-CBC-PKCS5Padding解密数据时出现填充错误,java,encryption,aes,jce,Java,Encryption,Aes,Jce,我编写了如下两个函数来加密和解密数据 public static void encrypt() throws Exception { // Add the BouncyCastle Provider //Security.addProvider(new BouncyCastleProvider()); // Generate the key byte[] keyBytes = "AAAAAAAAAAAAAAAA".getBytes(); SecretKeySpec key

我编写了如下两个函数来加密和解密数据

public static void encrypt() throws Exception {
    // Add the BouncyCastle Provider
    //Security.addProvider(new BouncyCastleProvider());


// Generate the key
byte[] keyBytes = "AAAAAAAAAAAAAAAA".getBytes();
SecretKeySpec   key = new SecretKeySpec(keyBytes, "AES");

// Generate the IV
byte[] ivBytes  = "AAAAAAAAAAAAAAAA".getBytes();
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

// Create the cipher object and initialize it
Cipher          cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);

// Read all bytes from a file into a bytes array
byte[] inputBytes = GCM.readFile("input");
byte[] cipherBytes = cipher.doFinal(inputBytes);

BufferedOutputStream  outputStream = new BufferedOutputStream(new FileOutputStream("output.enc"));
outputStream.write(cipherBytes);

outputStream.close();   
}

public static void decrypt() throws Exception {
    // Add the BouncyCastle Provider
     //Security.addProvider(new BouncyCastleProvider());

 // Generate the key
 byte[] keyBytes = "AAAAAAAAAAAAAAAA".getBytes();
 SecretKeySpec   key = new SecretKeySpec(keyBytes, "AES");

 // Generate the IV
 byte[] ivBytes  = "AAAAAAAAAAAAAAAA".getBytes();
 IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

 // Create the cipher object and initialize it
 Cipher          cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
 cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);

 // Read all bytes from a file into a bytes array
 byte[] cipherBytes = GCM.readFile("ouput.enc");
 byte[] decBytes = cipher.doFinal(cipherBytes);

 BufferedOutputStream  outputStream = new BufferedOutputStream(new FileOutputStream("regen.plain"));
 outputStream.write(decBytes);
 outputStream.close();   
}
我意识到代码的键设置为
“aaaaaaaaaaaa”.getBytes()
;不过,请容忍我,因为这只是一个例子

当我运行程序时,我得到以下堆栈跟踪:-

Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
    at javax.crypto.Cipher.doFinal(DashoA13*..)
    at GCM.decrypt(GCM.java:80)
    at GCM.main(GCM.java:90)
我很难弄清楚为什么会遇到这个错误。有没有关于我如何解决这个问题的提示

[编辑]
似乎当我写出数据时,总共有16个字节,但当我读回数据时,只有15个字节。

可能的问题(除非是打字错误)您写入
output.enc
,但在更新时从
output.enc

读取:那么,这很容易,修复读取文件的部分,因为密文需要为N*blocksize,因此为16字节。我没有看到任何其他明显的错误