-2

I have this snippet, Not sure why I am getting irregular results with this snippet.

Clue: Works well with a short string of fewer than 200 characters but when the string is in the ranges of 260 characters and above, it throws a javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes.

      Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
      byte[] key = "secret_key".getBytes(StandardCharsets.UTF_8);
      SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
      cipher.init(Cipher.ENCRYPT_MODE, secretKey);
      byte[] cipherText = cipher.doFinal(request.getBytes(StandardCharsets.UTF_8));
      String encryptedText = Base64.encodeBase64String(cipherText);
clifford_owino
  • 462
  • 1
  • 6
  • 24

1 Answers1

4

Clue: Input length not multiple of 16 bytes

Please note you have asked AES/ECB/NoPadding cipher mode.

AES is a block cipher - encrypting data per block (128 bit = 16 bytes). If the input is not multiple of 16 bytes, padding is used to fill the input length to multiples of the block size. You have specified NoPadding parameter, then the input is required to have multiple of 16 bytes. (nothing to do with length over 200 characters).

Another issue is using the ECB mode. Please do not use it until really not justified.

I have a few examples you could use.

gusto2
  • 11,210
  • 2
  • 17
  • 36
  • thanks for the lead, let me review. I'm handling a vendor integration thus have to conform to their standard – clifford_owino Nov 17 '20 at 20:09
  • 1
    @clifford_owino They need to put *something* in the last bytes, right? So what do they put in? Zero valued bytes maybe, for old PHP code? If that's the case, please update your question. PS, if you don't know, **decrypt** a standard ciphertext they created (with the correct key of course) using `NoPadding` and they look at the bytes. – Maarten Bodewes Nov 17 '20 at 20:58
  • 1
    Plus an AES key must be exactly 16, 24 or 32 bytes, and should not be limited to valid characters as is the case if it is obtained from `String.getBytes()`; in particular it should never be a password or passphrase -- those are NOT keys for post-WW1 crypto. – dave_thompson_085 Nov 17 '20 at 21:00