Java Base64 Encode encodeBase64(String data)

Here you can find the source of encodeBase64(String data)

Description

Encodes a String as a base64 String.

License

LGPL

Parameter

Parameter Description
data a String to encode.

Exception

Parameter Description
UnsupportedEncodingException an exception

Return

a base64 encoded String.

Declaration

public static String encodeBase64(String data) throws UnsupportedEncodingException 

Method Source Code

//package com.java2s;
/**//from  w  ww  .j  a  va2s. c o  m
 * Converts a line of text into an array of lower case words using a
 * BreakIterator.wordInstance(). <p>
 *
 * This method is under the Jive Open Source Software License and was
 * written by Mark Imbriaco.
 *
 * @param text a String of text to convert into an array of words
 * @return text broken up into an array of words.
 */

import java.io.UnsupportedEncodingException;

public class Main {
    private static final int fillchar = '=';
    private static final String cvt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/";

    /**
     * Encodes a String as a base64 String.
     *
     * @param data a String to encode.
     * @return a base64 encoded String.
     * @throws UnsupportedEncodingException 
     */
    public static String encodeBase64(String data) throws UnsupportedEncodingException {
        return encodeBase64(data.getBytes("GBK"));
    }

    /**
     * Encodes a byte array into a base64 String.
     *
     * @param data a byte array to encode.
     * @return a base64 encode String.
     */
    public static String encodeBase64(byte[] data) {
        int c;
        int len = data.length;
        StringBuffer ret = new StringBuffer(((len / 3) + 1) * 4);
        for (int i = 0; i < len; ++i) {
            c = (data[i] >> 2) & 0x3f;
            ret.append(cvt.charAt(c));
            c = (data[i] << 4) & 0x3f;
            if (++i < len)
                c |= (data[i] >> 4) & 0x0f;

            ret.append(cvt.charAt(c));
            if (i < len) {
                c = (data[i] << 2) & 0x3f;
                if (++i < len)
                    c |= (data[i] >> 6) & 0x03;

                ret.append(cvt.charAt(c));
            } else {
                ++i;
                ret.append((char) fillchar);
            }

            if (i < len) {
                c = data[i] & 0x3f;
                ret.append(cvt.charAt(c));
            } else {
                ret.append((char) fillchar);
            }
        }
        return ret.toString();
    }
}

Related

  1. base64UrlDecode(final String encodedString)
  2. base64UrlEncode(final byte[] v)
  3. encodeBASE64(InputStream in, OutputStream out)
  4. encodeBase64(InputStream is, OutputStream os)
  5. encodeBase64(String data)
  6. toBase64(byte[] array)
  7. toBase64(byte[] aValue)
  8. toBase64(byte[] buf, int start, int length)
  9. toBase64(byte[] data)