Here you can find the source of decode(String in)
Parameter | Description |
---|---|
in | the string to base 64 decode |
Parameter | Description |
---|---|
IOException | if base 64 encoded string is invalid |
public static byte[] decode(String in) throws IOException
//package com.java2s; /**/*from w w w . j a v a 2s . co m*/ * Copyright 2012 NetDigital Sweden AB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; public class Main { private static final byte[] base64CharsTo6BitNibbles = new byte[128]; /** * Base 64 decodes the specified string. * * @param in the string to base 64 decode * @return the base 64 decoded byte array * @throws IOException if base 64 encoded string is invalid */ public static byte[] decode(String in) throws IOException { int len = in.length(); if (len % 4 != 0) { throw new IOException("Length of base 64 encoded string must be a multiple of 4"); } while (len > 0 && in.charAt(len - 1) == '=') { len--; } int oLen = (len * 3) / 4; byte[] out = new byte[oLen]; int ip = 0; int iEnd = len; int op = 0; while (ip < iEnd) { int i0 = in.charAt(ip++); int i1 = in.charAt(ip++); int i2 = ip < iEnd ? in.charAt(ip++) : 'A'; int i3 = ip < iEnd ? in.charAt(ip++) : 'A'; if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) { throw new IOException("Illegal character in base64 encoded data"); } int b0 = base64CharsTo6BitNibbles[i0]; int b1 = base64CharsTo6BitNibbles[i1]; int b2 = base64CharsTo6BitNibbles[i2]; int b3 = base64CharsTo6BitNibbles[i3]; if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) { throw new IOException("Illegal character in base64 encoded data."); } int o0 = (b0 << 2) | (b1 >>> 4); int o1 = ((b1 & 0xf) << 4) | (b2 >>> 2); int o2 = ((b2 & 3) << 6) | b3; out[op++] = (byte) o0; if (op < oLen) { out[op++] = (byte) o1; } if (op < oLen) { out[op++] = (byte) o2; } } return out; } }