Reputation: 887
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?
Upvotes: 3
Views: 1011
Reputation: 109532
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.
Upvotes: 1
Reputation: 8806
Base64 works on blocks of 3 bytes, and the =
padding is there to bring the output size up to a multiple of 3. This padding is optional, and if is not there then you can simply add it manually by checking the array length before trying to decode using the Java code.
Upvotes: 0