DBMNG数据库管理与应用

所有存在都是独创。
当前位置:首页 > 经验分享 > Java组件

针对JDK7的自定义base64解码Base64Decoder

jdk8开始已经含有base64编解码方法。这里是针对jdk7的实现,使用方法:Base64Decoder.decode(String str);

package mybase64.decrypt;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;


class Base64Decoder extends FilterInputStream {

	private static final char[] chars = { 'A', 'B', 'C', 'D', 'E', 'F', 'G',
			'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
			'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
			'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
			'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', '+', '/' };

	// A mapping between char values and six-bit integers
	private static final int[] ints = new int[128];
	static {
		for (int i = 0; i < 64; i++) {
			ints[chars[i]] = i;
		}
	}

	private int charCount;
	private int carryOver;

	/***
	 * Constructs a new Base64 decoder that reads input from the given
	 * InputStream.
	 *
	 * @param in
	 *            the input stream
	 */
	public Base64Decoder(InputStream in) {
		super(in);
	}

	/***
	 * Returns the next decoded character from the stream, or -1 if end of
	 * stream was reached.
	 *
	 * @return the decoded character, or -1 if the end of the input stream is
	 *         reached
	 * @exception IOException
	 *                if an I/O error occurs
	 */
	public int read() throws IOException {
		// Read the next non-whitespace character
		int x;
		do {
			x = in.read();
			if (x == -1) {
				return -1;
			}
		} while (Character.isWhitespace((char) x));
		charCount++;

		// The '=' sign is just padding
		if (x == '=') {
			return -1; // effective end of stream
		}

		// Convert from raw form to 6-bit form
		x = ints[x];

		// Calculate which character we're decoding now
		int mode = (charCount - 1) % 4;

		// First char save all six bits, go for another
		if (mode == 0) {
			carryOver = x & 63;
			return read();
		}
		// Second char use previous six bits and first two new bits,
		// save last four bits
		else if (mode == 1) {
			int decoded = ((carryOver << 2="">> 4)) & 255;
			carryOver = x & 15;
			return decoded;
		}
		// Third char use previous four bits and first four new bits,
		// save last two bits
		else if (mode == 2) {
			int decoded = ((carryOver << 4="">> 2)) & 255;
			carryOver = x & 3;
			return decoded;
		}
		// Fourth char use previous two bits and all six new bits
		else if (mode == 3) {
			int decoded = ((carryOver << 6="">
本站文章内容,部分来自于互联网,若侵犯了您的权益,请致邮件chuanghui423#sohu.com(请将#换为@)联系,我们会尽快核实后删除。
Copyright © 2006-2023 DBMNG.COM All Rights Reserved. Powered by DEVSOARTECH            豫ICP备11002312号-2

豫公网安备 41010502002439号