clifford_owino
clifford_owino

Reputation: 463

IllegalBlockSizeException: Input length not multiple of 16 bytes AES/ECB/NoPadding

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);

Upvotes: -2

Views: 2553

Answers (1)

gusto2
gusto2

Reputation: 12075

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.

Upvotes: 4

Related Questions