BadPaddingException:在android解密块中损坏了pad块

时间:2014-11-01 21:05:04

标签: java android encryption badpaddingexception

我知道这个问题已被多次询问,但它似乎与我的代码无关。

我在解密时遇到异常:

" javax.crypto.BadPaddingException:pad block corrupted"

我的代码是:

private static byte[] appendIvToEncryptedData(byte[] eData, byte[] iv) throws Exception {
       ByteArrayOutputStream os = new ByteArrayOutputStream();
       os.write(eData);
       os.write(iv);
       return os.toByteArray();
    }

protected static byte[] dataEncryption(byte[] plainText)
    throws Exception {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "Crypto");
    byte [] iv = new byte[Constants.AES_BYTE_LENGTH];
    random.nextBytes(iv);
    AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
    SecretKeySpec secretKeySpec = new SecretKeySpec(mAESKey, "AES");
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, paramSpec);
    return appendIvToEncryptedData(cipher.doFinal(plainText), cipher.getIV());
}


protected static byte[] dataDecryption(byte[] encrypted)
    throws Exception {
    int ivIndex = encrypted.length - Constants.AES_BYTE_LENGTH;
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    SecretKeySpec secretKeySpec = new SecretKeySpec(mAESKey, "AES");
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, 
            new IvParameterSpec(encrypted, ivIndex, Constants.AES_BYTE_LENGTH));

    return cipher.doFinal(encrypted);
}

在dataDecryption()函数中调用cipher.doFinal()时抛出异常。此外,调用SecureRandom会收到此警告:" Android 4.3及更早版本的潜在不安全随机数。阅读https://android-developers.blogspot.com/2013/08/some-  securerandom-thoughts.html了解更多信息。"

我使用RandomAccessFile和FileOutputStream读取和写入文件,因此我直接使用字节数组。

我已经看过这个问题并修改了我的代码,但仍然无法正常工作:

Encryption error on Android 4.2

顺便说一下,我在一台设备上加密,另一台设备解密。

这是我的堆栈跟踪:

11-01 20:57:14.820: I/Exception(26336): javax.crypto.BadPaddingException: pad block corrupted
11-01 20:57:14.820: I/Exception(26336):     at com.android.org.bouncycastle.jce.provider.JCEBlockCipher.engineDoFinal(JCEBlockCipher.java:701)
11-01 20:57:14.820: I/Exception(26336):     at javax.crypto.Cipher.doFinal(Cipher.java:1106)
11-01 20:57:14.820: I/Exception(26336):     at com.example.example.KeyManagement.dataDecryption(KeyManagement.java:132)
11-01 20:57:14.820: I/Exception(26336):     at com.example.example.SecureReceiving$1.onEvent(SecureReceiving.java:86)
11-01 20:57:14.820: I/Exception(26336):     at android.os.FileObserver$ObserverThread.onEvent(FileObserver.java:125)
11-01 20:57:14.820: I/Exception(26336):     at android.os.FileObserver$ObserverThread.observe(Native Method)
11-01 20:57:14.820: I/Exception(26336):     at android.os.FileObserver$ObserverThread.run(FileObserver.java:88)

希望你能提前帮助我。

1 个答案:

答案 0 :(得分:2)

您忘记从密文中删除IV。

尝试:

return cipher.doFinal(encrypted, 0, ivIndex);

而不是

return cipher.doFinal(encrypted);

dataDecryption方法中。