package com.greenautomation.pkeytool;

import java.util.Arrays;
import java.io.ByteArrayOutputStream;

/**
 * Base 64 utilities.<p>
 *
 * Copyright 2003 Green Automation, Inc.<p>
 *
 * This file is part of pkeytool.<p>
 *
 * pkeytool is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.<p>
 *
 * pkeytool is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.<p>
 *
 * You should have received a copy of the GNU General Public License
 * along with pkeytool; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * @author David Green &lt;green@couchpotato.net&gt;
 * @version $Id: Base64.java,v 1.1 2003/03/06 07:12:45 green Exp $
 */
public final class Base64 {

    private static final char[] BASE64_CHARS = {
        '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 int[] BASE64_VALUES = new int[128];

    static {
        Arrays.fill(BASE64_VALUES, -1);
        for (int i=0; i < BASE64_CHARS.length; i++) {
            BASE64_VALUES[BASE64_CHARS[i]] = i;
        }
    }

    public static char[] encode(byte[] in) {

        char[] out = new char[(in.length + 2) / 3 * 4]; // base64 is 4:3
        int accum = -1; // the accumulator
        int outPtr = 0; // pointer into the out[] array

        for (int i=0; i < in.length; i++) {
            int b = in[i] < 0 ? 256 + in[i] : in[i];
            switch (i % 3) {
                case 0:
                    out[outPtr++] = BASE64_CHARS[b / 4];
                    accum = (b % 4) * 16;
                    break;
                case 1:
                    out[outPtr++] = BASE64_CHARS[accum + (b / 16)];
                    accum = (b % 16) * 4;
                    break;
                case 2:
                    out[outPtr++] = BASE64_CHARS[accum + (b / 64)];
                    out[outPtr++] = BASE64_CHARS[b % 64];
                    accum = -1; // done with this iteration
            }
        }
        if (accum >= 0) { // there's still a little data left over...
            out[outPtr++] = BASE64_CHARS[accum];
        }
        while (outPtr % 4 != 0) { // add padding
            out[outPtr++] = '=';
        }
        return out;

    }

    public static byte[] decode(char[] in) {

        int accum = -1;
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        for (int i=0; i < in.length; i++) {

            int value = BASE64_VALUES[in[i]];

            if (value < 0) { // padding or invalid data
                break;
            }

            switch (i % 4) {
                case 0:
                    accum = value * 4;
                    break;
                case 1:
                    out.write(accum + value / 16);
                    accum = (value % 16) * 16;
                    break;
                case 2:
                    out.write(accum + value / 4);
                    accum = (value % 4) * 64;
                    break;
                case 3:
                    out.write(accum + value);
                    break;
            }
        }

        return out.toByteArray();

    }

    /**
     * Strips all non-base64 characters from the input.
     * @param in the input.
     * @return the stripped output.
     */
    public static char[] strip(char[] in) {

        StringBuffer out = new StringBuffer();
        for (int i=0; i < in.length; i++) {
            if (BASE64_VALUES[in[i]] >= 0) {
                out.append(in[i]);
            }
        }

        return out.toString().toCharArray();

    }

}