Java Base64 Convert to fromBase64(final String input)

Here you can find the source of fromBase64(final String input)

Description

Convert Base64 string to byte array.

License

Open Source License

Parameter

Parameter Description
input Base64 string.

Return

Converted byte array.

Declaration

public static byte[] fromBase64(final String input) 

Method Source Code

//package com.java2s;
// and/or modify it under the terms of the GNU General Public License 

public class Main {
    /**/*from  ww  w.  j  a  v a  2s.c  om*/
     * Convert Base64 string to byte array.
     * 
     * @param input
     *            Base64 string.
     * @return Converted byte array.
     */
    public static byte[] fromBase64(final String input) {
        String tmp = input.replace("\r\n", "");
        if (tmp.length() % 4 != 0) {
            throw new IllegalArgumentException("Invalid base64 input");
        }
        int len = (tmp.length() * 3) / 4;
        int pos = tmp.indexOf('=');
        if (pos > 0) {
            len -= tmp.length() - pos;
        }
        byte[] decoded = new byte[len];
        char[] inChars = new char[4];
        int j = 0;
        int[] b = new int[4];
        for (pos = 0; pos != tmp.length(); pos += 4) {
            tmp.getChars(pos, pos + 4, inChars, 0);
            b[0] = getIndex(inChars[0]);
            b[1] = getIndex(inChars[1]);
            b[2] = getIndex(inChars[2]);
            b[3] = getIndex(inChars[3]);
            decoded[j++] = (byte) ((b[0] << 2) | (b[1] >> 4));
            if (b[2] < 64) {
                decoded[j++] = (byte) ((b[1] << 4) | (b[2] >> 2));
                if (b[3] < 64) {
                    decoded[j++] = (byte) ((b[2] << 6) | b[3]);
                }
            }
        }
        return decoded;
    }

    /**
     * Get index of given char.
     * 
     * @param ch
     * @return
     */
    private static int getIndex(final char ch) {
        if (ch == '+') {
            return 62;
        }
        if (ch == '/') {
            return 63;
        }
        if (ch == '=') {
            return 64;
        }
        if (ch < ':') {
            return (52 + (ch - '0'));
        }
        if (ch < '[') {
            return (ch - 'A');
        }
        if (ch < '{') {
            return (26 + (ch - 'a'));
        }
        throw new IllegalArgumentException("fromBase64");
    }
}

Related

  1. base64ToByte(String data)
  2. base64ToByteArray(String data)
  3. base64ToFile(String base64Code, String targetPath)
  4. fromBase64(byte[] buf, int start, int length)
  5. fromBase64(final String encoded)
  6. fromBase64(String base64)
  7. fromBase64(String base64Text)
  8. fromBase64(String data)
  9. fromBase64(String s)