Skip to content

Instantly share code, notes, and snippets.

@rickyclarkson
Created April 30, 2010 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rickyclarkson/385329 to your computer and use it in GitHub Desktop.
Save rickyclarkson/385329 to your computer and use it in GitHub Desktop.
package uk.org.netvu.util;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import java.io.ByteArrayOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
public class Base64Encoder {
private static final Logger log = Logger.getLogger(Base64Encoder.class);
public static String encode(String s) {
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
final Base64OutputStream out = new Base64OutputStream(bOut);
try {
out.write(s.getBytes());
out.flush();
}
catch (IOException ex) {
if (log.isEnabledFor(Level.DEBUG)) {
log.debug(ex.getMessage());
}
}
return bOut.toString();
}
}
class Base64OutputStream extends FilterOutputStream {
Base64OutputStream(ByteArrayOutputStream os) {
super(os);
}
@Override
public void write(byte[] data) throws IOException {
for (byte aData : data) {
write(aData);
}
}
public void write(byte b) throws IOException {
inbuf[i] = b;
i++;
if (i == 3) {
super.write(toBase64[(inbuf[0] & 0xFC) >> 2]);
super.write(toBase64[((inbuf[0] & 0x03) << 4) |
((inbuf[1] & 0xF0) >> 4)]);
super.write(toBase64[((inbuf[1] & 0x0F) << 2) |
((inbuf[2] & 0xC0) >> 6)]);
super.write(toBase64[inbuf[2] & 0x3F]);
col += 4;
i = 0;
if (col >= 76) {
super.write('\n');
col = 0;
}
}
}
@Override
public void flush() throws IOException {
if (i == 1) {
super.write(toBase64[(inbuf[0] & 0xFC) >> 2]);
super.write(toBase64[(inbuf[0] & 0x03) << 4]);
super.write('=');
super.write('=');
} else if (i == 2) {
super.write(toBase64[(inbuf[0] & 0xFC) >> 2]);
super.write(toBase64[((inbuf[0] & 0x03) << 4) |
((inbuf[1] & 0xF0) >> 4)]);
super.write(toBase64[(inbuf[1] & 0x0F) << 2]);
super.write('=');
}
}
private static final char[] toBase64 =
{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'
};
private int col = 0;
private int i = 0;
private final byte[] inbuf = new byte[3];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment