FileDocCategorySizeDatePackage
Base64Converter.javaAPI DocApache Ant 1.703871Wed Dec 13 06:16:22 GMT 2006org.apache.tools.ant.util

Base64Converter

public class Base64Converter extends Object
BASE 64 encoding of a String or an array of bytes. Based on RFC 1421.

Fields Summary
private static final char[]
ALPHABET
public static final char[]
alphabet
Provided for BC purposes
Constructors Summary
Methods Summary
public java.lang.Stringencode(java.lang.String s)
Encode a string into base64 encoding.

param
s the string to encode.
return
the encoded string.

    // CheckStyle:ConstantNameCheck ON


                         
        
        return encode(s.getBytes());
    
public java.lang.Stringencode(byte[] octetString)
Encode a byte array into base64 encoding.

param
octetString the byte array to encode.
return
the encoded string.

        int bits24;
        int bits6;

        char[] out = new char[((octetString.length - 1) / 3 + 1) * 4];
        int outIndex = 0;
        int i = 0;

        while ((i + 3) <= octetString.length) {
            // store the octets
            bits24 = (octetString[i++] & 0xFF) << 16;
            bits24 |= (octetString[i++] & 0xFF) << 8;
            bits24 |= octetString[i++];

            bits6 = (bits24 & 0x00FC0000) >> 18;
            out[outIndex++] = ALPHABET[bits6];
            bits6 = (bits24 & 0x0003F000) >> 12;
            out[outIndex++] = ALPHABET[bits6];
            bits6  = (bits24 & 0x00000FC0) >> 6;
            out[outIndex++] = ALPHABET[bits6];
            bits6 = (bits24 & 0x0000003F);
            out[outIndex++] = ALPHABET[bits6];
        }
        if (octetString.length - i == 2) {
            // store the octets
            bits24 = (octetString[i] & 0xFF) << 16;
            bits24 |= (octetString[i + 1] & 0xFF) << 8;
            bits6 = (bits24 & 0x00FC0000) >> 18;
            out[outIndex++] = ALPHABET[bits6];
            bits6 = (bits24 & 0x0003F000) >> 12;
            out[outIndex++] = ALPHABET[bits6];
            bits6 = (bits24 & 0x00000FC0) >> 6;
            out[outIndex++] = ALPHABET[bits6];

            // padding
            out[outIndex++] = '=";
        } else if (octetString.length - i == 1) {
            // store the octets
            bits24 = (octetString[i] & 0xFF) << 16;
            bits6 = (bits24 & 0x00FC0000) >> 18;
            out[outIndex++] = ALPHABET[bits6];
            bits6 = (bits24 & 0x0003F000) >> 12;
            out[outIndex++] = ALPHABET[bits6];

            // padding
            out[outIndex++] = '=";
            out[outIndex++] = '=";
        }
        return new String(out);