Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Base64 encode gives different results than C base64 encode

Tags:

java

c

base64

I try to encode this byte array:

[237, 217, 204, 218, 109, 227, 157, 145, 35, 152, 85, 142, 182, 180, 120, 8]

Using Java library org.apache.commons.codec.binary.Base64.encodeBase64 and org.bouncycastle.util.encoders.Base64.encode this is the results:

[55, 100, 110, 77, 50, 109, 51, 106, 110, 90, 69, 106, 109, 70, 87, 79, 116, 114, 82, 52, 67, 65, 61, 61]

(note the double '=' padding character at the end)

Using base64.c Copyright (c) 1995-2001 Kungliga Tekniska Högskolan (Royal Institute of Technology, Stockholm, Sweden) this is the output:

[55, 100, 110, 77, 50, 109, 51, 106, 110, 90, 69, 106, 109, 70, 87, 79, 116, 114, 82, 52, 67, 66, 72, 114]

Can anyone explain why? How can I make the Java/C library works the same way?

like image 660
Alvins Avatar asked Sep 29 '26 10:09

Alvins


1 Answers

Every Base64 ASCII character holds 6 bits information (26 = 64), so 4 Base64 characters hold 3 bytes information. You have 16 bytes, so one byte remains at the end, needing 2 Base64 characters, and to make the group up to 4 chars, two padding =s are added.

Mind: with JavaSE 8 came a class Base64 to replace several older class around.

Base64 has several fields of application, with various little changes: padding can be left out, line breaks added to limit line length, and so on. Java 8's Base64 even has an option for a non-compatible URL and file name safeversion, where + and / are replaced.

like image 93
Joop Eggen Avatar answered Oct 02 '26 00:10

Joop Eggen



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!