Base64 encoding in Java / Groovy

37,989

Solution 1

Apache Commons has many utilities:

Binary Package: http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html

Download: http://commons.apache.org/codec/download_codec.cgi

Solution 2

The preferred way to do this in groovy is:

 def encoded = "Hello World".bytes.encodeBase64().toString()
 assert encoded == "SGVsbG8gV29ybGQ="
 def decoded = new String("SGVsbG8gV29ybGQ=".decodeBase64())
 assert decoded == "Hello World"

Solution 3

You could use the open source Base64Coder library

import biz.source_code.base64Coder.Base64Coder

@Grab(group='biz.source_code', module='base64coder', version='2010-09-21')

String s1 = Base64Coder.encodeString("Hello world")
String s2 = Base64Coder.decodeString("SGVsbG8gd29ybGQ=")

Solution 4

Implement your own method like this :)

public class Coder {
private static final String base64code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

public static String encodeAsBase64(String toEncode) {
    return encodeAsBase64(toEncode.getBytes())
}

public static String encodeAsBase64(byte[] toEncode) {
    int pos = 0;
    int onhand = 0;

    StringBuffer buffer = new StringBuffer();
    for(byte b in toEncode) {
        int read = b;
        int m;
        if(pos == 0) {
            m = (read >> 2) & 63;
            onhand = read & 3;
            pos = 1;
        } else if(pos == 1) {
            m = (onhand << 4) + ((read >> 4) & 15);
            onhand = read & 15;
            pos = 2;
        } else if(pos == 2) {
            m = ((read >> 6) & 3) + (onhand << 2);
            onhand = read & 63;
            buffer.append(base64code.charAt(m));
            m = onhand;
            onhand = 0;
            pos  = 0;
        }
        buffer.append(base64code.charAt(m));
    }
    while(pos > 0 && pos < 4) {
        pos++;
        if(onhand == -1) {
            buffer.append('=');
        } else {
            int m = pos == 2 ? onhand << 4 : (pos == 3 ? onhand << 2 : onhand);
            onhand = -1;
            buffer.append(base64code.charAt(m));
        }
    }
    return buffer.toString()
}

}

Share:
37,989
Josh K
Author by

Josh K

Me I'm a software engineer living in New York City. Currently I'm available for consulting work, previously I founded JAKT a leading design and development consultancy that uses technology to solve problems for entrepreneurs and cor­po­ra­tions. You can read more about me at joshuakehn.com or @joshkehn. Common Links: Guidelines for Constructive Questions FAQ

Updated on January 15, 2020

Comments

  • Josh K
    Josh K over 4 years

    What is the proper way to convert a byte [] to a Base64 string in Java? Better yet would be Grails / Groovy because it tells me that the encodeAsBase64() function is deprecated. The sun.misc.BASE64Encoder package isn't recommended for use and outputs a different size string on some Windows platforms.