I am trying to decrypt and encrypt data with AES and sending it over the network with TCP. My wanted my algorithm to work this way:
Encryption:
- Generate two base64'd salts with
!
as padding (e.g. !9W5AQcaNjaWF2Q!) - Arrange message in this way [salt][data][salt]
- Encrypt message with AES/CBC/PKCS5Padding, 128-bit key length
- Send [identifier][base64-message]
However if I try to decrypt the base-64 message the first 128-bits don't contain the salt but random data.
When I try to decrypt the message, I notice that the first 128 bits look like garbage: (I'm sure those are 128 bit)
What I expect (256 bit salt)
!R6NYI2DxsRt4Fb6PKZA+Itr0D5jqFo!ayy!CcHGYvN/1vW79KemKLQ39OjVcGI/3y!
What I get
�*M�y��n�']e_PKZA+Itr0D5jqFo!ayy!CcHGYvN/1vW79KemKLQ39OjVcGI/3y!
Also, here is my code for encryption and decryption
Decryption
private byte[] decryptAES(SecretKeySpec key, byte[] text) {
byte[] decryptedText = null;
try {
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
decryptedText = cipher.doFinal(text);
} catch (GeneralSecurityException e) {
System.out.println("[WARNING] Could not decrypt data, wrong key?");
}
return decryptedText;
}
Encryption
private byte[] encryptAES(SecretKeySpec key, byte[] text) {
byte[] encryptedText = null;
try {
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
encryptedText = cipher.doFinal(text);
} catch (GeneralSecurityException e) {
System.out.println("[ERROR] Could not encrypt data!");
e.printStackTrace();
}
return encryptedText;
}
How can I modify these functions to do proper encryption / decryption?