Encrypt and decrypt with AES and Base64 encoding

Fundamentally, there is an asymmetry between your encrypt function and your decrypt function. When you encrypt you perform an AES encrypt and then a base64 encode, when you decrypt you don't first undo the base64 encoding step.

I think that there's something wrong with your base64 encoding as well as [ shouldn't appear in a base64 encoded string.

Looking at the documentation for org.apache.commons.codec.binary.Base64 you should be able to do this on encode:

String encryptedValue = Base64.encodeBase64String(encValue);

and this on decode:

byte[] encValue = Base64.decodeBase64(encryptedValue);

The line

String encryptedValue = encryptedByteValue.toString();

is the problem. The type of encryptedByteValue is byte[] and calling toString on it isn't what you want to do there. Instead try

String encryptedValue = Base64.getEncoder().encodeToString(encValue);

Then use Base64.decodeBase64(encryptedValue) in decrypt. You must do that prior to attempting to decrypt though. You must undo the operations in the reverse order of the encrypt method.


Your Order for encrypt: getBytes, encrypt, encode, toString
Your Order for decrypt(Wrong*): getBytes, decrypt, decode, toString

Two problems:

  1. As someone already mentioned you should reverse the order of operations for decryption. You are not doing that.
  2. encrypt gives you 16 bytes, encode 24 bytes, but toString gives 106 bytes. Something to do with invalid chars taking up additional space.

Note: Also, you don't need to call generateKey() twice.

Fix problem #1 by using the reverse order for decryption.
Correct order for decrypt: getBytes, decode, decrypt, toString

Fix problem #2 by replacing xxx.toString() with new String(xxx). Do this in both the encrypt and decrypt functions.

Your decrypt should look like this:

c.init(Cipher.DECRYPT_MODE, key)
val decodedValue = new Base64().decode(encryptedValue.getBytes())
val decryptedVal = c.doFinal(decodedValue)
return new String(decryptedVal)

This should give you back "dude5"