user2531569
user2531569

Reputation: 619

Java convert Base 64 value to Hex

I have generated Base64 encoded value using below Scala code:

println(Base64.getEncoder.encodeToString("E5E9FA1BA31ECD1AE84F75CAAA474F3A".getBytes(StandardCharsets.UTF_8)))
YxRfXk827kPgkmMUX15PNg==

Now I am trying to convert "YxRfXk827kPgkmMUX15PNg==" to Hex. I tried with below Java code but no luck:

public static void main(String[] args) throws DecoderException {
        String guid = "RTVFOUZBMUJBMzFFQ0QxQUU4NEY3NUNBQUE0NzRGM0E=";
        byte[] hexString = Hex.decodeHex(guid);
        System.out.println(hexString);

Exception in thread "main" org.apache.commons.codec.DecoderException: Illegal hexadecimal character R at index 0

When I explored I found below working Java code:

String guid = "YxRfXk827kPgkmMUX15PNg==";
byte[] decoded = Base64.decodeBase64(guid);
String hexString = Hex.encodeHexString(decoded);
System.out.println(hexString);

4535453946413142413331454344314145383446373543414141343734463341

But here Base64 values is getting decoded and then converted to Hex. I am trying to figure out if there is a way we can directly convert Base64 to Hex? Please excuse as it looks like a duplicate question and thanks in advance.

Upvotes: 0

Views: 2015

Answers (1)

Randy
Randy

Reputation: 9819

Since it is a String, it already has a way to get the ByteArray. Don't decode the Base64, simply request the bytes from the String:

public static void main(String[] args) {
    String guid = "YxRfXk827kPgkmMUX15PNg==";
    String hexString = Hex.encodeHexString(guid.getBytes());
    System.out.println(hexString);
}

This basically means you only have to convert your string to a Byte[].

You can see that the business logic code is very simple and that the original text and the hex encoded are the same by trying to decode them in a test:

// actual business logic
public String hexEncoder(String content) {
    return Hex.encodeHexString(content.getBytes());
}

// input and assertion
@Test
public void hexEncoder() throws DecoderException {
    String guid = "YxRfXk827kPgkmMUX15PNg==";

    String hexString = hexEncoder(guid);
    String hexDecoded = new String(Hex.decodeHex(hexString));

    // no need to decode Base64 but might be useful for `printLn` or debugging
    String s = new String(Base64.decodeBase64(guid));
    String s1 = new String(Base64.decodeBase64(hexDecoded));

    assertEquals(s, s1);
}

Upvotes: 2

Related Questions