40

I am using the below function in Java to convert an encrypted String into hex format:

public static String toHex(byte [] buf) {
    StringBuffer strbuf = new StringBuffer(buf.length * 2);
    int i;
    for (i = 0; i < buf.length; i++) {
        if (((int) buf[i] & 0xff) < 0x10) {
            strbuf.append("0");
        }
        strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
    }
    return strbuf.toString();
}

Now I want to convert that hex string back into a byte array. How can I do that?

For example,

(1) Plain Text = 123
(2) Encrypted Text = «h>kq*«¬Mí“~èåZ  \}?
(3) Encrypted Text in Hex = f263575e7b00a977a8e9a37e08b9c215feb9bfb2f992b2b8f11e

I can go from (2) to (3), but how do I go from (3) back to (2)?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bhavik Ambani
  • 6,557
  • 14
  • 55
  • 86
  • aa to Ra. One Movie no kamal chhe. you can join me in my chat room http://chat.stackoverflow.com/rooms/6137/ – Lucifer Jan 17 '12 at 05:47
  • 2
    What's a Back byte array? Is that different from a byte array? – Keith Irwin Jan 17 '12 at 06:00
  • How to convert binary/byte string into hex? http://stackoverflow.com/questions/29603046/decrypt-string-in-java-which-was-encrypted-using-symmetric-key-in-php/29603246?noredirect=1#29603046 – Scorpion Apr 13 '15 at 11:29

3 Answers3

113

The accepted answer does not consider leading zeros which may cause problems

This question answers it. Depending on whether you want to see how its done or just use a java built-in method. Here are the solutions copied from this and this answers respectively from the SO question mentioned.

Option 1: Util method

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

Option 2: One-liner build-in

import javax.xml.bind.DatatypeConverter;

public static String toHexString(byte[] array) {
    return DatatypeConverter.printHexBinary(array);
}

public static byte[] toByteArray(String s) {
    return DatatypeConverter.parseHexBinary(s);
}
Community
  • 1
  • 1
dARKpRINCE
  • 1,538
  • 2
  • 13
  • 22
  • your answer help me with http://stackoverflow.com/a/25790612/173149, thanks +1 – gavenkoa Sep 11 '14 at 14:56
  • +1 for the one-liner option using classes already provided with Java. – Zeimyth Oct 21 '14 at 17:47
  • For the string `56276BE1`, it gives me bytes of `86, 39, 107, -31`. But an other application written in C# gives me `86, 39, 107, 225` for the same hex string. Which one is true? – Fer Jun 26 '15 at 08:47
  • Both are correct. C# handles bytes differently than Java. In Java byte value is between -127 and 127, while C# has 0 to 255. – dARKpRINCE Jun 26 '15 at 12:19
  • 4
    The one-liner built-in seems to be not-so-built-in anymore on Java 9 though, as simply importing `javax.xml.bind.DatatypeConverter` does not work. – ionizer Dec 08 '17 at 18:25
  • 1
    as of Java 17 there is now an officially provided method `java.util.HexFormat.of().parseHex(s)` – Dave L. Dec 13 '21 at 20:54
47
 String s="f263575e7b00a977a8e9a37e08b9c215feb9bfb2f992b2b8f11e";
 byte[] b = new BigInteger(s,16).toByteArray();
Kushan
  • 10,657
  • 4
  • 37
  • 41
  • 6
    This did not give me the result I was looking for, but the simple one-liner method in dARKpRINCE's response did. – Jeremy Goodell Apr 07 '15 at 21:41
  • `cs.setBytes(1,new BigInteger(regReportId,16).toByteArray());` this worked when i have to pass RAW datatype to Oracle sproc – Dilip Oct 06 '16 at 16:12
  • The `new BigInteger(s,16).toByteArray();` is not correct. I input a 34-length hex string, and output a 18-length bytes. What I want is a 17-length bytes – Ninja Aug 11 '17 at 11:02
  • I think this gives wrong result sometimes. for instance, it gives 17 bytes for A85565ED63B893F5A3EF85D88819D484. but it should be 16 bytes – Adem Sep 06 '17 at 21:00
  • this gives the wrong results; DarkPrince "util method" works correctly for me. – Blisterpeanuts Mar 03 '21 at 18:54
6

I found that the DatatypeConverter.parseHexBinary is more costly (two times) than:

org.apache.commons.codec.binary.Hex(str.toCharArray())
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rony Joy
  • 124
  • 1
  • 6
  • This is more costly than DatatypeConverter, since Apache commons is an additional library (dependency, size, etc) - while DatatypeConverter is part of the JDK. – foo Jun 13 '19 at 16:39