Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java convert Base64 to Hex String [duplicate]

Tags:

java

hex

base64

I have one Base64 String YxRfXk827kPgkmMUX15PNg== I want to convert it into 63145F5E4F36EE43E09263145F5E4F36

So I think scenario would be like this I have to first decode Base64 string and than convert it into Hex

My code is given below

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

String guid = "YxRfXk827kPgkmMUX15PNg==";
byte[] decoded = Base64.decodeBase64(guid);
try {
    System.out.println(new String(decoded, "UTF-8") + "\n");
} catch (UnsupportedEncodingException e1) {
    e1.printStackTrace();
}

Above code gives c_^O6?C??c_^O6

But I don't know How to convert this string into Hex string. So it gives the 63145F5E4F36EE43E09263145F5E4F36 output.

So please help me to fix this issue.

like image 946
user3441151 Avatar asked Dec 15 '22 01:12

user3441151


2 Answers

Since you are already using Apache Common Codec:

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

Using standard Java libraries:

String guid = "YxRfXk827kPgkmMUX15PNg==";
byte[] decoded = Base64.getDecoder().decode(guid);
System.out.println(String.format("%040x", new BigInteger(1, decoded)));
like image 161
Shakti Dash Avatar answered Dec 31 '22 23:12

Shakti Dash


Hey try this code it gives the expected output

import java.util.Base64;

/**
*
* @author hemants
*/
public class NewClass5 {

    public static void main(String[] args) {
        String guid = "YxRfXk827kPgkmMUX15PNg==";
        byte[] decoded = Base64.getDecoder().decode(guid);
        System.out.println(toHex(decoded));
    }
    private static final char[] DIGITS
            = {'0', '1', '2', '3', '4', '5', '6', '7',
                '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    public static final String toHex(byte[] data) {
        final StringBuffer sb = new StringBuffer(data.length * 2);
        for (int i = 0; i < data.length; i++) {
            sb.append(DIGITS[(data[i] >>> 4) & 0x0F]);
            sb.append(DIGITS[data[i] & 0x0F]);
        }
        return sb.toString();
    }

}

Output

63145F5E4F36EE43E09263145F5E4F36
like image 36
Hemant Sangle Avatar answered Dec 31 '22 21:12

Hemant Sangle