0

I have a problem with decrypting a message using AES. At the end when I expect a message, e.g.

ala123

Instead of that I receive sth like:

...6�b}\7�k�8�vFP�8~%��_zժF��FW��O_e���ó������������ala123

The message I pass to encryption is built as:

  • cipher key is SHA-256 from AES_TOKEN
  • cipher IV is some characters, which are then stored in the message (at the beginnig)
  • decrypted message is wrapped up into Base64

The question is why at the end I eventually receive my expected message, but with a lot of rubbish chars at the beggining?

My encryption code is:

private static final String AES_TOKEN = "my_very_secret_token";

// encrypted is base64 string
public String decrypt(String encrypted) throws Exception {
    byte[] decrypted = Base64.getDecoder().decode(encrypted);
    return new String(aesDecrypt(decrypted), "UTF-8");
}

private byte[] aesDecrypt(byte[] message) throws Exception {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

    byte[] token = MessageDigest.getInstance("SHA-256").digest(AES_TOKEN.getBytes());
    SecretKeySpec secretKey = new SecretKeySpec(token, "AES");

    IvParameterSpec iv = new IvParameterSpec(Arrays.copyOf(message, 16));

    cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
    return cipher.doFinal(message);
}
Dariusz Mydlarz
  • 2,940
  • 6
  • 31
  • 59
  • Possible duplicate of [AES encryption, got extra trash characters in decrypted file](http://stackoverflow.com/questions/29029410/aes-encryption-got-extra-trash-characters-in-decrypted-file) – azurefrog Jan 04 '16 at 15:44
  • 1
    @azurefrog If it was a padding issue, the extra characters ought to be at the end, not the beginning of the message, I think – Ctx Jan 04 '16 at 15:49
  • 3
    is the IV part of the message to be decrypted? you don't remove it before doing the decryption – jonk Jan 04 '16 at 15:56
  • @Dariusz If PunDefeated is right, then only the first 16 bytes should be garbage, but there are 51 garbage characters. It seems that there is something else going on. Can you include the encryption? – Artjom B. Jan 04 '16 at 19:29
  • @ArtjomB. I guess some header could be present which decrypts to unprintable characters. As long as the IV is within the ciphertext CBC will still decrypt the original plaintext. The header would have to be x times the blocksize of course. Another option is that we don't see the complete plaintext; the "..." part is probably added by Dariusz or the development environment. – Maarten Bodewes Jan 04 '16 at 22:07
  • @PunDefeated was right, I wasn't aware of fact that IV should be removed from decryption. Thanks all for help :) – Dariusz Mydlarz Jan 05 '16 at 07:05

1 Answers1

3

It looks like you aren't removing the IV from the beginning of message after reading it in to iv. That would explain the garbage being at the start of the decrypted message.

PunDefeated
  • 566
  • 5
  • 18