0

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?

6
  • The whole point of Base64 is to avoid converting raw binary into a string as it tends to corrupt the data. i..e don't do what you did on the first line. use a byte[] instead. Commented Oct 29, 2020 at 11:01
  • For sure I did not understand you correctly; it still isn't the desired output Commented Oct 29, 2020 at 11:11
  • On one hand you wrote that you want to decode, on the other hand you encode: Base64.getEncoder() Commented Oct 29, 2020 at 11:14
  • You got a point there Commented Oct 29, 2020 at 11:22
  • 1
    @BenjaminZach check now. Commented Oct 29, 2020 at 11:32

2 Answers 2

2

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();
          }
Sign up to request clarification or add additional context in comments.

2 Comments

Output is 6C000-800000000000, how to get rid of the additional 0-?
@BenjaminZach This was because negative value passed to Integer.toString(). Updated code. Check now.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.