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)
?
To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array. byte[] val = new byte[str. length() / 2]; Now, take a for loop until the length of the byte array.
To obtain a string in hexadecimal format from this array, we simply need to call the ToString method on the BitConverter class. As input we need to pass our byte array and, as output, we get the hexadecimal string representing it. string hexString = BitConverter. ToString(byteArray);
We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument. Here is a simple program showing how to convert String to byte array in java.
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); }
String s="f263575e7b00a977a8e9a37e08b9c215feb9bfb2f992b2b8f11e"; byte[] b = new BigInteger(s,16).toByteArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With