Java tutorial
//package com.java2s; // it under the terms of the GNU General Public License as published by public class Main { private static final String BASE64_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz./"; /** * <p>The inverse function of the above.</p> * * <p>Converts a string representing the encoding of some bytes in Base-64 * to their original form.</p> * * @param str the Base-64 encoded representation of some byte(s). * @return the bytes represented by the <code>str</code>. * @throws NumberFormatException if <code>str</code> is <code>null</code>, or * <code>str</code> contains an illegal Base-64 character. * @see #toBase64(byte[]) */ public static final byte[] fromBase64(String str) { int len = str.length(); if (len == 0) { throw new NumberFormatException("Empty string"); } byte[] a = new byte[len + 1]; int i, j; for (i = 0; i < len; i++) { try { a[i] = (byte) BASE64_CHARS.indexOf(str.charAt(i)); } catch (ArrayIndexOutOfBoundsException x) { throw new NumberFormatException("Illegal character at #" + i); } } i = len - 1; j = len; try { while (true) { a[j] = a[i]; if (--i < 0) { break; } a[j] |= (a[i] & 0x03) << 6; j--; a[j] = (byte) ((a[i] & 0x3C) >>> 2); if (--i < 0) { break; } a[j] |= (a[i] & 0x0F) << 4; j--; a[j] = (byte) ((a[i] & 0x30) >>> 4); if (--i < 0) { break; } a[j] |= (a[i] << 2); j--; a[j] = 0; if (--i < 0) { break; } } } catch (Exception ignored) { } try { // ignore leading 0-bytes while (a[j] == 0) { j++; } } catch (Exception x) { return new byte[1]; // one 0-byte } byte[] result = new byte[len - j + 1]; System.arraycopy(a, j, result, 0, len - j + 1); return result; } }