Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Base64 deterministic (Apache Commons lib or otherwise)?

I'm using the Base64 encoder from the Apache Commons library. Now either something funny is going on with my runtime/IDE, or their implementation of Base64 encoding (or Base64 as a specification) is non-deterministic:

val test = Base64.encodeBase64("hello".getBytes).toString
val test2 = Base64.encodeBase64("hello".getBytes).toString
val test3 = Base64.encodeBase64("hello".getBytes).toString

Each of the above produce different results. Is this expected? I'm writing this in Scala...

like image 774
Lawrence Wagerfield Avatar asked May 14 '26 20:05

Lawrence Wagerfield


1 Answers

The equivalent Java code for the Scala code which you have posted will be :

String test = Base64.encodeBase64("hello".getBytes()).toString();
String test2 = Base64.encodeBase64("hello".getBytes()).toString();
String test3 = Base64.encodeBase64("hello".getBytes()).toString();

This will print the toString() of the byte[] array object for each Base64.encodeBase64("hello".getBytes()) which will be different objects and hence different output to the console. It executes the toString() method of Object class which, according to the Javadocs says :

Returns a string representation of the object.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object.

To get the correct String representation , use Arrays.toString() method. A sample Java code to print the correct result is as below :

String test = Arrays.toString(Base64.encodeBase64("hello".getBytes()));
String test2 = Arrays.toString(Base64.encodeBase64("hello".getBytes()));
String test3 = Arrays.toString(Base64.encodeBase64("hello".getBytes()));
like image 100
AllTooSir Avatar answered May 17 '26 09:05

AllTooSir



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!