I'm trying to implement a string conversion from Base64 to Hex, that must yield the same results as
this website. Which means for example (Base64: bACAAAAAAAA=) is deconverted to (Hex: 6c00800000000000). This implementation in Javascript yields the correct output. So I tried to implement the equivalent in Java:
private static String base64ToHex(String input) {
byte[] raw = Base64.getDecoder().decode(input.getBytes());
String result = "";
for (int i = 0; i < raw.length; i++) {
String hex = Integer.toString(raw[i], 16);
result += (hex.length() == 2 ? hex : '0' + hex);
}
return result.toUpperCase();
}
Unfortunately this does not give the required output. So could you please give me hint about what I am missing?
# Answer 1
Try below - You need to decode, not encode. Consider only value from decoded, ignore sign part. i.e take only absolute value, using Math.abs().
private static String base64ToHex(String input) {
byte[] raw = Base64.getDecoder().decode(input.getBytes());
String result = "";
for (int i = 0; i < raw.length; i++) {
String hex = Integer.toString(Math.abs(raw[i]), 16);
result += (hex.length() == 2 ? hex : '0' + hex);
}
return result.toUpperCase();
}
# Answer 2
private static String base64ToHex(String input) {
byte[] raw = Base64.getDecoder().decode(
input.getBytes(StandardCharsets.US_ASCII));
StringBuilder result = new StringBuilder(raw.length * 2);
for (byte b : raw) {
result.append(String.format("%02X", b & 0xFF));
}
return result.toString();
}
The problem is that java byte is signed, hence the masking & 0xFF.