How to Base64 encode a Java object using org.apache.commons.codec.binary.base64?

66,016

Actually the commons-codec version and specific Sun internal version you are using do give the same results. I think you thought they were giving different versions because you are implicitly calling toString() on an array when you do:

System.out.println(org.apache.commons.codec.binary.Base64.encodeBase64(baos.toByteArray()));

which is definitely does not print out the array contents. Instead, that will only print out the address of the array reference.

I've written the following program to test the encoders against each other. You'll see from the output below that the give the same results:

import java.util.Random;

public class Base64Stuff
{
    public static void main(String[] args) {
        Random random = new Random();
        byte[] randomBytes = new byte[32];
        random.nextBytes(randomBytes);

        String internalVersion = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.encode(randomBytes);
        byte[] apacheBytes =  org.apache.commons.codec.binary.Base64.encodeBase64(randomBytes);
        String fromApacheBytes = new String(apacheBytes);

        System.out.println("Internal length = " + internalVersion.length());
        System.out.println("Apache bytes len= " + fromApacheBytes.length());
        System.out.println("Internal version = |" + internalVersion + "|");
        System.out.println("Apache bytes     = |" + fromApacheBytes + "|");
        System.out.println("internal equal apache bytes?: " + internalVersion.equals(fromApacheBytes));
    }
}

And here's the output from a run of it:

Internal length = 44
Apache bytes len= 44
Internal version = |Kf0JBpbxCfXutxjveYs8CXMsFpQYgkllcHHzJJsz9+g=|
Apache bytes     = |Kf0JBpbxCfXutxjveYs8CXMsFpQYgkllcHHzJJsz9+g=|
internal equal apache bytes?: true
Share:
66,016
Ta Sas
Author by

Ta Sas

Updated on December 30, 2020

Comments

  • Ta Sas
    Ta Sas over 3 years

    I've been trying to do an object serialization and Base64 encode the result. It works with Sun's lib:

    Bean01 bean01 = new Bean01();
    bean01.setDefaultValues();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    new ObjectOutputStream( baos ).writeObject( bean01 );
    System.out.println(Base64.encode(baos.toByteArray()));
    

    This works fine. However, I would like to do the same using org.apache.commons.codec.binary.base64, but this does not return the same string:

    System.out.println(org.apache.commons.codec.binary.Base64.encodeBase64(baos.toByteArray()));

    What would be the correct way to achieve the correct Base64 encoding of a byteArray using Apache's encoder?