Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to base-64 encode a hex string

Tags:

java

hex

base64

I am trying to base-64 encode a hex string (copied below) but the values that I get from the Java8 call to encode to base64 do not match what I am getting on different online converters. I am trying to figure out what steps I am missing (or missteps I am taking):

//hexString is 07050600030102
Base64.getEncoder().encodeToString(hexString.getBytes(StandardCharsets.UTF_8));

//output I am getting from Java8 ic copied below:
MDcwNTA2MDAwMzAxMDI=

//online converters:
BwUGAAMBAg==
like image 802
ali haider Avatar asked Sep 09 '26 09:09

ali haider


1 Answers

This doesn't do what you expect it to:

hexString.getBytes(StandardCharsets.UTF_8)

That's just encoding the hex string as UTF-8 - you want to parse the hex string, so that each pair of hex digits ends up as a single byte. The fact that the base64 result is different is just because the bytes you're base64-encoding are different.

To parse a hex string into bytes, you can use Guava (amongst other libraries)

byte[] bytes = BaseEncoding.base16().decode(hexString);
String base64 = BaseEncoding.base64().encode(bytes);
like image 68
Jon Skeet Avatar answered Sep 12 '26 00:09

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!