我知道这个问题已经被问过好几次了,但它似乎不适用于我的代码。
解密时出现异常:
“javax.crypto.BadPaddingException:垫块损坏”
我的代码是:
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 读写文件,所以我直接使用字节数组。
我已经查看了另一个问题并按照它的说明修改了我的代码,但仍然无法正常工作:
顺便说一句,我在一个设备中加密并在另一个不同的设备中解密。
这是我的堆栈跟踪:
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)
希望你能帮助我,在此先感谢。