0

My input hex is

C30A010000003602000F73B32F9ECA00E9F2F2E9

I need to convert it to the following base 64 encoded String:

wwoBAAAANgIAD3OzL57KAOny8uk=

I can simulate this transformation on this site: http://www.asciitohex.com/ but I cant seem to get this transformation working in Java using the various base64 encoder Utils that are suggested on this site and other places on the web. For example,

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;

public class Test {

    public static void main(final String args[]) throws DecoderException {

    String hexString = "C30A010000003602000F73B32F9ECA00E9F2F2E9";

    String output = new String(Base64.encodeBase64String(hexString.getBytes()));

    System.out.println(output);

}

However the output for this is something different:

QzMwQTAxMDAwMDAwMzYwMjAwMEY3M0IzMkY5RUNBMDBFOUYyRjJFOQ==

Can anyone suggest how to get this transformation working successfully?

Thanks

Kash.
  • 242
  • 1
  • 3
  • 15

1 Answers1

3

Basically, hexString.getBytes() doesn't do what you expect it to. It's just encoding the string as a byte sequence in your platform default encoding - it's got nothing to do with hex.

You need to decode from hex to byte[] to start with. Additionally, you don't need to call the String constructor with another string. As you're already using Apache Commons Codec, it makes sense to use the Hex class for the decoding. I would also separate out the steps for clarity:

String hexString = "C30A010000003602000F73B32F9ECA00E9F2F2E9";
byte[] rawData = Hex.decodeHex(hexString.toCharArray());
String output = Base64.encodeBase64String(rawData);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194