NordicSemiconductor / Android-nRF-Mesh-Library

The Bluetooth Mesh Provisioner and Configurator library.
https://www.nordicsemi.com/
BSD 3-Clause "New" or "Revised" License
414 stars 177 forks source link

Please harden/fix MeshParserUtils.toByteArray() #453

Closed NanaDada closed 2 years ago

NanaDada commented 3 years ago

Describe the bug There are a few issues with the current implementation of MeshParserUtils.toByteArray()

public static byte[] toByteArray(String hexString) {
        int len = hexString.length();
        byte[] bytes = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i + 1), 16));
        }
        return bytes;
    }

It's going to fail:

  1. on a little endian system.
  2. if hexString is of odd length.
  3. if the hexString starts with "0x".
roshanrajaratnam commented 2 years ago

Hi this is just a utility function to convert a hex string to a byte array

  1. This would just convert to a byte array irrespective of the endianness
  2. This also assumes the hex string is of even length and not sure why you would use a hex string of odd length.
  3. If the hex string starts with 0x you can omit this.
philips77 commented 2 years ago

It also doesn't check if the input is not null, but it's an internal method of the library. Made public, as Java can't restrict it to compilation unit.