IllegalBlockSizeException:输入长度不是 16 字节的倍数 AES/ECB/NoPadding

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

我有这个片段,不知道为什么我用这个片段得到不规则的结果。

线索:适用于少于 200 个字符的短字符串,但当字符串在 260 个字符及以上的范围内时,它会抛出 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);

线索: Input length not multiple of 16 bytes

请注意您已询问 AES/ECB/NoPadding 密码模式。

AES 是一种块密码 - 按块(128 位 = 16 字节)加密数据。如果输入不是 16 字节的倍数,则使用 padding 将输入长度填充为块大小的倍数。您指定了 NoPadding 参数,然后 输入必须是 16 字节的倍数 。 (与长度超过 200 个字符无关)。

另一个问题是使用 ECB mode。请不要使用它,直到真的没有理由。

我有几个 examples 你可以用。