Search code examples
javascalabase64apache-commons

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...


Solution

  • 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()));