0

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:

  1. Generate two base64'd salts with ! as padding (e.g. !9W5AQcaNjaWF2Q!)
  2. Arrange message in this way [salt][data][salt]
  3. Encrypt message with AES/CBC/PKCS5Padding, 128-bit key length
  4. 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?

KeksArmee
  • 1,349
  • 14
  • 21
  • 1
    I think I'm pretty ignorant for finding out with one Google search that I have to XOR the first 16 bytes with the IV, sorry – KeksArmee Nov 21 '15 at 20:04
  • justed marked duplicate :P – KeksArmee Nov 21 '15 at 20:17
  • 1
    Be aware you have no authentication/integrity protection, so are vulnerable to a padding oracle attack. Using GCM Cipher Mode is maybe better [more info](http://www.javacodegeeks.com/2012/05/secure-encryption-in-java.html). – wdk Nov 21 '15 at 20:32
  • 1
    You should look into [JNCryptor](https://github.com/RNCryptor/JNCryptor) which provides all kinds of useful encryption methods surrounding AES and includes authentication. It's also very protable, because there are RNCryptor ports for many languages. – Artjom B. Nov 21 '15 at 22:04

0 Answers0