Java (Android) Расшифровка сообщения с подключенным IV
Я генерирую случайный IV, этот IV присоединяется (в простых байтах) к передней части зашифрованного сообщения, как показано ниже;
public String encrypt(String plainText, byte[] encryptionKey) throws Exception {
SecretKeySpec key = new SecretKeySpec(encryptionKey, "AES");
cipher.init(Cipher.ENCRYPT_MODE, key, iV);
byte[] data = new byte[iV.getIV().length + plainText.getBytes("UTF-8").length];
// Merge together plain IV and encrypted cipher text
System.arraycopy(iV.getIV(), 0, data, 0, iV.getIV().length);
System.arraycopy(cipher.doFinal(plainText.getBytes("UTF-8")), 0, data, iV.getIV().length, plainText.getBytes("UTF-8").length);
return Base64.encodeToString(data, Base64.DEFAULT);
}
Сообщение отправляется между устройствами с помощью WiFi Direct. Это обрабатывается в моем MainActivity;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
crypto.iV = new IvParameterSpec(Arrays.copyOf(readBuf, 16));
// Construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
Log.d(TAG, readMessage);
try {
String decryptMsg = crypto.decrypt(readMessage, SECRET_KEY);
// Present the message
(chatFragment).pushMessage("Buddy (decrypt): " + decryptMsg);
Log.d(TAG, decryptMsg);
} catch (Exception e) {
e.printStackTrace();
}
// Present the message (comment out after testing!)
//(chatFragment).pushMessage("Buddy (encrypt): " + readMessage);
break;
Во время расшифровки происходит сбой с предупреждением;
04-04 14: 55: 05.770: W / System.err (9847): javax.crypto.IllegalBlockSizeException: последний блок не завершен при расшифровке
04-04 14: 55: 05.789: W / System.err (9847): at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal (BaseBlockCipher.java:850)
04-04 14: 55: 05.790: W / System.err (9847): at javax.crypto.Cipher.doFinal (Cipher.java:1340)
04-04 14: 55: 05.790: W / System.err (9847): на com.example.cryptochat.Crypto.decrypt (Crypto.java:52)
04-04 14: 55: 05.790: W / System.err (9847): на com.example.cryptochat.MainActivity.handleMessage (MainActivity.java:463)
Проблема заключается в методе расшифровки, но я не уверен, что делаю неправильно. Этот метод ниже;
public String decrypt(String cipherText, byte[] encryptionKey) throws Exception {
SecretKeySpec key = new SecretKeySpec(encryptionKey, "AES");
cipher.init(Cipher.DECRYPT_MODE, key, iV);
String decrypt = new String(cipher.doFinal( Base64.decode(cipherText, Base64.DEFAULT)));
decrypt = new String(Arrays.copyOfRange(decrypt.getBytes(), 16, decrypt.getBytes().length));
return decrypt;
}