この質問が何度か寄せられていることは知っていますが、私のコードではうまくいかないようです。
復号化時に例外が発生します:
「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 を呼び出すと、次の警告が表示されました 。
私は 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)
よろしくお願いします。