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

标签 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 = 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();   
}

我意识到代码的 key 设置为 "AAAAAAAAAAAAAAAA".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个字节。

最佳答案

关于您的更新:嗯,这很简单,修复读取文件的部分,因为密文需要为 N * block 大小,即 16 字节。我没有看到任何其他明显的错误。

关于java - 使用 AES-CBC-PKCS5Padding 解密数据时出现填充错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14263950/

相关文章:

java - Android:保留先前 Activity 的值

php - 如何实现对加密数据库字段的搜索

php - 使用 AES_DECRYPT 获取数据

java - 无法连接到 SSL 端口 63149 上的 Lotus Notes DIIOP

java - 如何区分 Spring Data Jpa 中的 DataAccessException 中的数据库连接失败错误与其他异常

javascript - 404 未找到加密值

java - 使用 Rijndael 在 .Net 中加密的 java 中解密文件时出错

c# - C# 和 Swift 中的 RNCryptor,RNCryptorError 错误 2

java - 获取两天之间的差值(减法)

php - 使用 Javascript/PHP 验证公钥