Java Base64 Encode base64Encode(byte[] aData)

Here you can find the source of base64Encode(byte[] aData)

Description

Codifica um dado array de bytes usando codificacao Base64 como especificado na RFC-2045 (sessao 6.8)

License

Open Source License

Parameter

Parameter Description
aData os dados a serem codificados

Return

os dados de aData codificados em Base64

Declaration

public static String base64Encode(byte[] aData) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    private static byte[] mBase64EncMap, mBase64DecMap;

    /**//from w w w  .j a v  a  2s.c om
     * Codifica um dado array de bytes usando codificacao Base64
     * como especificado na RFC-2045 (sessao 6.8)
     *
     * @param aData os dados a serem codificados
     * @return os dados de <var>aData</var> codificados em Base64
     * @exception IllegalArgumentException se NULL ou um array vazio foi passado
     */
    public static String base64Encode(byte[] aData) {
        if ((aData == null) || (aData.length == 0))
            throw new IllegalArgumentException("Can not encode NULL or empty byte array.");

        byte encodedBuf[] = new byte[((aData.length + 2) / 3) * 4];

        // 3-byte to 4-byte conversion
        int srcIndex, destIndex;
        for (srcIndex = 0, destIndex = 0; srcIndex < aData.length - 2; srcIndex += 3) {
            encodedBuf[destIndex++] = mBase64EncMap[(aData[srcIndex] >>> 2) & 077];
            encodedBuf[destIndex++] = mBase64EncMap[(aData[srcIndex + 1] >>> 4) & 017
                    | (aData[srcIndex] << 4) & 077];
            encodedBuf[destIndex++] = mBase64EncMap[(aData[srcIndex + 2] >>> 6) & 003
                    | (aData[srcIndex + 1] << 2) & 077];
            encodedBuf[destIndex++] = mBase64EncMap[aData[srcIndex + 2] & 077];
        }

        // Convert the last 1 or 2 bytes
        if (srcIndex < aData.length) {
            encodedBuf[destIndex++] = mBase64EncMap[(aData[srcIndex] >>> 2) & 077];
            if (srcIndex < aData.length - 1) {
                encodedBuf[destIndex++] = mBase64EncMap[(aData[srcIndex + 1] >>> 4) & 017
                        | (aData[srcIndex] << 4) & 077];
                encodedBuf[destIndex++] = mBase64EncMap[(aData[srcIndex + 1] << 2) & 077];
            } else {
                encodedBuf[destIndex++] = mBase64EncMap[(aData[srcIndex] << 4) & 077];
            }
        }

        // Add padding to the end of encoded data
        while (destIndex < encodedBuf.length) {
            encodedBuf[destIndex] = (byte) '=';
            destIndex++;
        }

        String result = new String(encodedBuf);
        return result;
    }
}

Related

  1. base64Encode(byte[] aData)
  2. base64Encode(byte[] buf)
  3. base64Encode(byte[] buf, int tw)
  4. base64Encode(byte[] bytes)
  5. base64Encode(byte[] bytes)