Here you can find the source of base64Decode(String b64)
Parameter | Description |
---|---|
b64 | The Base-64 encoded string. |
Parameter | Description |
---|
public static byte[] base64Decode(String b64) throws IOException
//package com.java2s; // under the terms of the GNU General Public License as published by the Free import java.io.ByteArrayOutputStream; import java.io.IOException; public class Main { /** Base-64 characters. */ private static final String BASE_64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /** Base-64 padding character. */ private static final char BASE_64_PAD = '='; /**//from ww w .ja v a 2 s . c o m * Decode a Base-64 string into a byte array. * * @param b64 The Base-64 encoded string. * @return The decoded bytes. * @throws java.io.IOException If the argument is not a valid Base-64 * encoding. */ public static byte[] base64Decode(String b64) throws IOException { ByteArrayOutputStream result = new ByteArrayOutputStream(); int state = 0, i; byte temp = 0; for (i = 0; i < b64.length(); i++) { if (Character.isWhitespace(b64.charAt(i))) { continue; } if (b64.charAt(i) == BASE_64_PAD) { break; } int pos = BASE_64.indexOf(b64.charAt(i)); if (pos < 0) { throw new IOException("non-Base64 character " + b64.charAt(i)); } switch (state) { case 0: temp = (byte) (pos - BASE_64.indexOf('A') << 2); state = 1; break; case 1: temp |= (byte) (pos - BASE_64.indexOf('A') >>> 4); result.write(temp); temp = (byte) ((pos - BASE_64.indexOf('A') & 0x0f) << 4); state = 2; break; case 2: temp |= (byte) ((pos - BASE_64.indexOf('A') & 0x7f) >>> 2); result.write(temp); temp = (byte) ((pos - BASE_64.indexOf('A') & 0x03) << 6); state = 3; break; case 3: temp |= (byte) (pos - BASE_64.indexOf('A') & 0xff); result.write(temp); state = 0; break; default: throw new Error("this statement should be unreachable"); } } if (i < b64.length() && b64.charAt(i) == BASE_64_PAD) { switch (state) { case 0: case 1: throw new IOException("malformed Base64 sequence"); case 2: for (; i < b64.length(); i++) { if (!Character.isWhitespace(b64.charAt(i))) { break; } } // We must see a second pad character here. if (b64.charAt(i) != BASE_64_PAD) { throw new IOException("malformed Base64 sequence"); } i++; // Fall-through. case 3: i++; for (; i < b64.length(); i++) { // We should only see whitespace after this. if (!Character.isWhitespace(b64.charAt(i))) { System.err.println(b64.charAt(i)); throw new IOException("malformed Base64 sequence"); } } } } else { if (state != 0) { throw new IOException("malformed Base64 sequence"); } } return result.toByteArray(); } }