Base64位java加密算法

package mains;

import java.util.ArrayList;
import java.util.List;

import com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64DecoderStream;
import com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64EncoderStream;

import sun.misc.BASE64Encoder;

/***
 * Base64位加密算法.
 * @author Administrator xlaohe1
 *
 */
public class Base64Test {
	/*
	  	Base64 使用US-ASCII子集的64个字符,即大小写的26个英文字母,0-9,+,/。
		编码总是基于3个字符,每个字符用8位二进制表示,因此一共24位,再分为4四组,每组6位,表示一个Base64的值。
		Base64值为0就是A,为27的就是b。这样,每3个字符产生4位的Base64字符。如果被加密的字符串每3个一组,还剩1或2个字符,
		使用特殊字符"="补齐Base64的4字。
		
	 */
		
	private final static char[] BASE64ARR = {  
        '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', '+', '/'  
    };  

	
	public static void main(String[] args) {
		String src = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure."; 
		StringBuffer sb = new StringBuffer();
		byte[] buf = src.getBytes();
		for(byte b : buf) {
			sb.append(to8len(Integer.toBinaryString(b&0xff), 8));
		}
		String bin = toNstr(sb.toString(), 6, "0");
		StringBuffer newBuf = new StringBuffer(bin.length() / 6);
		for(int i = 0, len = bin.length(); i < len; i += 6) {
			newBuf.append(BASE64ARR[Integer.parseInt(bin.substring(i, i + 6), 2)]);
		}
		//System.out.println(toNstr(newBuf.toString(), 3, "="));
		System.out.println(newBuf.toString());
	}
	private static String to8len(String src, int n) {
		if(null == src || "".equals(src)) return "";
		if(src.length() >= n) return src;
		return to8len("0" + src, n);
	}
	private static String toNstr(String src, int mod, String c) {
		if(src.length() % mod == 0) return src;
		StringBuffer sb = new StringBuffer();
		sb.append(src);
		int i = 0, len = mod - src.length() % mod;
		while(i ++ < len) {
			sb.append(c);
		}
		return sb.toString();
	}

}

你可能感兴趣的:(java,算法,base64)