Java Base64 Decode decodeBase64(String data)

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

Description

Decodes a base64 String.

License

Open Source License

Parameter

Parameter Description
data a base64 encoded String to decode.

Return

the decoded String.

Declaration

public static String decodeBase64(String data) 

Method Source Code

//package com.java2s;
/**/*from   w  w w .  ja v a 2 s . com*/
 * $RCSFile$
 * $Revision: 18401 $
 * $Date: 2005-02-05 10:18:52 -0800 (Sat, 05 Feb 2005) $
 *
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
 *
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution, or a commercial license
 * agreement with Jive.
 */

import java.io.UnsupportedEncodingException;

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

    /**
     * Decodes a base64 String.
     *
     * @param data a base64 encoded String to decode.
     * @return the decoded String.
     */
    public static String decodeBase64(String data) {
        byte[] bytes = null;
        try {
            bytes = data.getBytes("ISO-8859-1");
        } catch (UnsupportedEncodingException uee) {
        }
        return decodeBase64(bytes);
    }

    /**
     * Decodes a base64 aray of bytes.
     *
     * @param data a base64 encode byte array to decode.
     * @return the decoded String.
     */
    public static String decodeBase64(byte[] data) {
        int c, c1;
        int len = data.length;
        StringBuffer ret = new StringBuffer((len * 3) / 4);
        for (int i = 0; i < len; ++i) {
            c = cvt.indexOf(data[i]);
            ++i;
            c1 = cvt.indexOf(data[i]);
            c = ((c << 2) | ((c1 >> 4) & 0x3));
            ret.append((char) c);
            if (++i < len) {
                c = data[i];
                if (fillchar == c)
                    break;

                c = cvt.indexOf(c);
                c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
                ret.append((char) c1);
            }

            if (++i < len) {
                c1 = data[i];
                if (fillchar == c1)
                    break;

                c1 = cvt.indexOf(c1);
                c = ((c << 6) & 0xc0) | c1;
                ret.append((char) c);
            }
        }
        return ret.toString();
    }
}

Related

  1. decode(String base64Code)
  2. decodeBase64(char[] data)
  3. decodeBASE64(InputStream in, OutputStream out)
  4. decodeBase64(InputStream is, OutputStream os)
  5. decodeBase64(String base64Data)
  6. decodeBase64(String data)
  7. decodeBASE64(String pEncoded)
  8. decodeBase64(String str)
  9. decodeBase64AsUtf8(String data)