/** * Provides static methods for encoding and decoding strings of base 64 * characters, such as those used for HTTP basic authorization. * * No warranty -- you may use this code in your own projects so long as you * preserve this message and the author tag below. * * @author Wes Biggs */ public class Base64 { private static final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; private static final int b64val(char c) { int b = alphabet.indexOf(c); return (b == -1) ? 0 : b; } private static final char b64char(int i) { return ((i >= 0) && (i < 64)) ? alphabet.charAt(i) : '='; } /** * Creates a base 64 encoding of the input text. * * @param f_text the String to be encoded. */ public static final String encode(String f_text) { StringBuffer output = new StringBuffer(); // read 3 chars, make 4 int l = f_text.length(); int a,b,c,d; for (int i = 0; i < l;) { b = c = d = 0; a = (int) f_text.charAt(i++); output.append(b64char(a >> 2)); if (i < l) { b = (int) f_text.charAt(i++); output.append(b64char((b >> 4) | ((a << 4) & 63))); if (i < l) { c = (int) f_text.charAt(i++); output.append(b64char((c >> 6) | ((b << 2) & 63))); output.append(b64char(c & 63)); } else { output.append(b64char((b << 2) & 63)); output.append('='); } } else { output.append(b64char((a << 4) & 63)); output.append("=="); } } return output.toString(); } /** * Decodes a base 64 encoding of a string. * * @param f_text the String to be decoded. */ public static final String decode(String f_text) { StringBuffer output = new StringBuffer(); for (int i = 0; (i + 3) < f_text.length();) { int a = b64val(f_text.charAt(i++)); int b = b64val(f_text.charAt(i++)); int c = b64val(f_text.charAt(i++)); int d = b64val(f_text.charAt(i++)); a = ((a << 2) & 255) | (b >> 4); b = ((b << 4) & 255) | (c >> 2); c = ((c << 6) & 255) | d; output.append((char) a); if (b != 0) output.append((char) b); if (c != 0) output.append((char) c); } return output.toString(); } }