0

How can I convert a char array of hex to byte array in Java? I don't want to convert char array to string for security reasons.

Is there any inbuilt library available for this conversion in Java 8?

Dino
  • 7,779
  • 12
  • 46
  • 85
Dark Matter
  • 300
  • 2
  • 15
  • 1
    What do you mean? How does security is compromised if converted to `String`? – Mushif Ali Nawaz Sep 24 '19 at 17:34
  • I can clear the char array by Arrays.fill but if converted to string it will be dependent on gc in java – Dark Matter Sep 24 '19 at 17:36
  • You might want to [check this answer](https://stackoverflow.com/a/9670279/5413565) – Mushif Ali Nawaz Sep 24 '19 at 17:42
  • 1
    @Mushif Ali Nawaz See [Why is char array preferred over String for passwords?](https://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords) – Nexevis Sep 24 '19 at 17:42
  • 2
    Possible duplicate of [Converting char\[\] to byte\[\]](https://stackoverflow.com/questions/5513144/converting-char-to-byte) – Mushif Ali Nawaz Sep 24 '19 at 17:43
  • Do you mean that each char value is a hexadecimal digit? Meaning, ASCII `0`–`9` or `a`–`f` or `A`–`F`? – VGR Sep 24 '19 at 17:57
  • @VGR yes the char array is randomly generated hexadecimal array I have to convert it to byte array, I tried Bytebuffer bytebuffer = StandardCharsets.UTF_8.encode(Charbuffer.wrap(chrarr)) but this is just doing the utf8 conversion not hex conversion – Dark Matter Sep 24 '19 at 18:07
  • Improved formatting and grammar – Dino Sep 25 '19 at 07:16

1 Answers1

0

There is no single Java SE method for it, but with Character.digit it’s fairly straightforward:

byte[] parse(char[] hex) {
    int len = hex.length;
    if (len % 2 != 0) {
        throw new IllegalArgumentException(
            "Even number of digits required");
    }

    byte[] bytes = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        int high = Character.digit(hex[i], 16);
        int low = Character.digit(hex[i + 1], 16);
        bytes[i / 2] = (byte) (high << 4 | low);
    }

    return bytes;
}
VGR
  • 40,506
  • 4
  • 48
  • 63