Here you can find the source of fromBase64(final String input)
Parameter | Description |
---|---|
input | Base64 string. |
public static byte[] fromBase64(final String input)
//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"); } }