Base 64 Encoding


I just spent a whole week for a twitter xAuth client. And I had to implement Base 64 encoding by myself.

/**
 * The Base 64 Alphabet.
 *
 * '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 static final byte[] BASE64_ALPHABET = {
    0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
    0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50,
    0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
    0x59, 0x5A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66,
    0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E,
    0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76,
    0x77, 0x78, 0x79, 0x7A, 0x30, 0x31, 0x32, 0x33,
    0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2B, 0x2F
};

public static String base64(final byte[] input) {

    if (input == null) {
        throw new NullPointerException("null input");
    }

    int count = input.length / 3;
    if (input.length % 3 > 0) {
        count++;
    }

    final byte[] output = new byte[count * 4];
    int index = 0;

    int pad = 0;
    int word;
    for (int i = 0; i < input.length; i += 3) {
        word = 0x00;
        for (int j = 0; j < 3; j++) {
            if ((i + j) < input.length) {
                word <<= 8;
                word |= (input[i + j] & 0xFF);
            } else {
                switch (j) {
                    case 1:
                        pad = 2;
                        word <<= 4;
                        break;
                    case 2:
                        pad = 1;
                        word <<= 2;
                        break;
                    default:
                        break;
                }
                break;
            }
        }
        for (int j = 0; j < pad; j++) {
            output[index + 3 - j] = '=';
        }
        for (int j = 3 - pad; j >= 0; j--) {
            output[index + j] = BASE64_ALPHABET[word & 0x3F];
            word >>= 6;
        }
        if (pad != 0) {
            break;
        }
        index += 4;
    }

    return new String(output);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s