david son
david son

Reputation: 23

Mismatch data when using different Base64 libraries

Currently using the Base64 conversion via the org.apache.commons.codec.binary.Base64 library. This was implemented as part of some older token generation we have which works fine. We are currently trying to drop this library and stick to using Java 8's in built Base64 library under utils. But this doesn't work due to mismatched characters as follows. Is there a way to over come this (other than using regex which I definitely don't wanna mess with)? Please advice. Thank you.

String value1 = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(aByteArray);
String value2 = java.util.Base64.getEncoder().encodeToString(aByteArray);

Sample outcome when using the org.apache.commons.codec.binary.Base64 library.

1111111111_22222_Some // value1

Sample outcome when using the java.util.Base64 library.

1111111111/22222/Some= // value2 

Notice the difference between / and _ plus the missing = sign. In different tokens you will see differences such as + sign vs - sign and so on.

I have tried options without padding and setting StandardCharsets.UTF_8 for the byte array being passed in ending up with same mismatched results.

Upvotes: 2

Views: 527

Answers (1)

k5_
k5_

Reputation: 5568

org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(aByteArray); creates a url safe base64 variant. (With _ and - as part of the encoding)

Using java.util.Base64.getEncoder().encodeToString(aByteArray); will create the "standard" base64 with "/" "=" and "+" as part of the encoding. That would not be url safe.

The Base64 class has a different encoder (Base64.getUrlEncoder()) for the url safe encoding variant:

java.util.Base64.getUrlEncoder().encodeToString(aByteArray) 

Edit:

to remove the optional padding you can use

java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(aByteArray);

Upvotes: 5

Related Questions