You can reconstruct bytes[]
from the converted string,
here's one way to do it:
public String fromHex(String hex) throws UnsupportedEncodingException {
hex = hex.replaceAll("^(00)+", "");
byte[] bytes = new byte[hex.length() / 2];
for (int i = 0; i < hex.length(); i += 2) {
bytes[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16));
}
return new String(bytes);
}
Another way is using DatatypeConverter
, from javax.xml.bind
package:
public String fromHex(String hex) throws UnsupportedEncodingException {
hex = hex.replaceAll("^(00)+", "");
byte[] bytes = DatatypeConverter.parseHexBinary(hex);
return new String(bytes, "UTF-8");
}
Unit tests to verify:
@Test
public void test() throws UnsupportedEncodingException {
String[] samples = {
"hello",
"all your base now belongs to us, welcome our machine overlords"
};
for (String sample : samples) {
assertEquals(sample, fromHex(toHex(sample)));
}
}
Note: the stripping of leading 00
in fromHex
is only necessary because of the "%040x"
padding in your toHex
method.
If you don't mind replacing that with a simple %x
,
then you could drop this line in fromHex
:
hex = hex.replaceAll("^(00)+", "");