1

I am using cipher to encrypt and decrypt byte arrays in android to send to a server. I am not using strings but I still receive the illegal block size exception.

                try {
                    byte[] cipherNameText = {};

                    KeyGenerator keygen = null;
                    keygen = KeyGenerator.getInstance("AES");
                    keygen.init(256);
                    SecretKey key= keygen.generateKey();

                    String name = nameEdit.getText().toString();

                    Cipher cipher = null;
                    cipher = Cipher.getInstance("AES_256/CBC/NoPadding");
                    SecureRandom iv = new SecureRandom();
                    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
                    cipherNameText = cipher.doFinal(name.getBytes(StandardCharsets.UTF_8));
                    byte[] iv1 = cipher.getIV();

                    HashMap<String, byte[]> map = new HashMap<>();
                    map.put("name",key.toString().getBytes(StandardCharsets.UTF_8));

                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (NoSuchPaddingException e) {
                    e.printStackTrace();
                } catch (BadPaddingException e) {
                    e.printStackTrace();
                } catch (IllegalBlockSizeException e) {
                    e.printStackTrace();
                } catch (InvalidKeyException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

2021-08-12 20:55:17.606 15222-15222/com.example.package W/System.err: javax.crypto.IllegalBlockSizeException: error:1e00006a:Cipher functions:OPENSSL_internal:DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH

2021-08-12 21:51:47.322 15606-15606/com.example.package W/System.err: at com.example.servertutorial.MainActivity$4.onClick(MainActivity.java:212)

^this points to "cipherNameText = cipher.doFinal(name.getBytes(StandardCharsets.UTF_8));"

mystack
  • 95
  • 8
  • By using `NoPadding`, you've promised that the data you're going to encrypt will have a length that is a multiple of the block size (16 bytes). Use a different padding mode, or pad the data yourself. See [this answer](https://stackoverflow.com/questions/59923645/what-exactly-does-the-nopadding-parameter-do-in-the-cipher-class) for more info. – Michael Aug 13 '21 at 05:51

1 Answers1

1

The problem, as Michael pointed out, was using NoPadding. The message size did not fit the block size of AES. Padding the message solves this.

Change:

                    cipher = Cipher.getInstance("AES_256/CBC/NoPadding");

To:

                            cipher = Cipher.getInstance("AES_256/CBC/PKCS5PADDING");
mystack
  • 95
  • 8