Base64编码原理

18 篇文章 0 订阅

转自 http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001399413803339f4bbda5c01fc479cbea98b1387390748000

Base64是一种用64个字符来表示任意二进制数据的方法。

用记事本打开exe、jpg、pdf这些文件时,我们都会看到一大堆乱码,因为二进制文件包含很多无法显示和打印的字符,所以,如果要让记事本这样的文本处理软件能处理二进制数据,就需要一个二进制到字符串的转换方法。Base64是一种最常见的二进制编码方法。

Base64的原理很简单,首先,准备一个包含64个字符的数组:

['A', 'B', 'C', ... 'a', 'b', 'c', ... '0', '1', ... '+', '/']

然后,对二进制数据进行处理,每3个字节一组,一共是3x8=24bit,划为4组,每组正好6个bit:

base64-encode

这样我们得到4个数字作为索引,然后查表,获得相应的4个字符,就是编码后的字符串。

所以,Base64编码会把3字节的二进制数据编码为4字节的文本数据,长度增加33%,好处是编码后的文本数据可以在邮件正文、网页等直接显示。

如果要编码的二进制数据不是3的倍数,最后会剩下1个或2个字节怎么办?Base64用\x00字节在末尾补足后,再在编码的末尾加上1个或2个=号,表示补了多少字节,解码的时候,会自动去掉。

Python内置的base64可以直接进行base64的编解码:

>>> import base64
>>> base64.b64encode('binary\x00string')
'YmluYXJ5AHN0cmluZw=='
>>> base64.b64decode('YmluYXJ5AHN0cmluZw==')
'binary\x00string'

由于标准的Base64编码后可能出现字符+和/,在URL中就不能直接作为参数,所以又有一种"url safe"的base64编码,其实就是把字符+和/分别变成-和_:

>>> base64.b64encode('i\xb7\x1d\xfb\xef\xff')
'abcd++//'
>>> base64.urlsafe_b64encode('i\xb7\x1d\xfb\xef\xff')
'abcd--__'
>>> base64.urlsafe_b64decode('abcd--__')
'i\xb7\x1d\xfb\xef\xff'

还可以自己定义64个字符的排列顺序,这样就可以自定义Base64编码,不过,通常情况下完全没有必要。

Base64是一种通过查表的编码方法,不能用于加密,即使使用自定义的编码表也不行。

Base64适用于小段内容的编码,比如数字证书签名、Cookie的内容等。

由于=字符也可能出现在Base64编码中,但=用在URL、Cookie里面会造成歧义,所以,很多Base64编码后会把=去掉:

# 标准Base64:
'abcd' -> 'YWJjZA=='
# 自动去掉=:
'abcd' -> 'YWJjZA'

去掉=后怎么解码呢?因为Base64是把3个字节变为4个字节,所以,Base64编码的长度永远是4的倍数,因此,需要加上=把Base64字符串的长度变为4的倍数,就可以正常解码了。

请写一个能处理去掉=的base64解码函数:

>>> base64.b64decode('YWJjZA==')
'abcd'
>>> base64.b64decode('YWJjZA')
Traceback (most recent call last):
  ...
TypeError: Incorrect padding
>>> safe_b64decode('YWJjZA')
'abcd'


实现代码

 

/**
 * BASE64转换工具
 * 
 
 */
public class Base64Util {
	private static final char intToBase64[] = {'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', '+', '/'};
	private static final byte base64ToInt[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
				-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
				-1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 
				-1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 
				17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 
				33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 };
	
	/**
	 * byte数组转换成BASE64字符串
	 * 
	 * @param data byte数组
	 * @return <b>String</b> BASE64字符串<b><br/>null</b> 转换失败
	 */
	public static String byteArrayToBase64(byte[] data) {
		if(data==null || data.length==0){
			return null;
		}
		int len = data.length;
		int groups = len/3;
		int nogroups = len-3*groups;
		int resultLen = (len+2)/3*4;
		StringBuffer result = new StringBuffer(resultLen);
		int cursor = 0;
		for(int i=0;i<groups;i++){
			int byte0 = data[cursor++]&0xff;
			int byte1 = data[cursor++]&0xff;
			int byte2 = data[cursor++]&0xff;
			result.append(intToBase64[byte0>>2]);
			result.append(intToBase64[(byte0<<4)&0x3f|(byte1>>4)]);
			result.append(intToBase64[(byte1<<2)&0x3f|(byte2>>6)]);
			result.append(intToBase64[byte2&0x3f]);
		}
		if(nogroups!=0){
			int byte0 = data[cursor++]&0xff;
			result.append(intToBase64[byte0>>2]);
			if(nogroups==1){
				result.append(intToBase64[(byte0<<4)&0x3f]);
				result.append("==");
			}else{
				int byte1 = data[cursor++]&0xff;
				result.append(intToBase64[(byte0<<4)&0x3f|(byte1>>4)]);
				result.append(intToBase64[(byte1<<2)&0x3f]);
				result.append('=');
			}
		}
		return result.toString();
    }
	
	/**
	 * BASE64字符串转换成byte数组
	 * 
	 * @param data BASE64字符串
	 * @return <b>String</b> byte数组<b><br/>null</b> 转换失败
	 */
	public static byte[] base64ToByteArray(String data) {
		if(StringUtil.isEmpty(data)){
			return null;
		}
		int len = data.length();
		int groups = len/4;
		if(groups*4!=len){
			return null;
		}
		int nogroups = 0;
		int fullGroups = groups;
		if(len!=0){
			if(data.charAt(len-1)=='='){
				nogroups++;
				fullGroups--;
			}
			if(data.charAt(len-2)=='='){
				nogroups++;
			}
		}
		byte[] result = new byte[groups*3-nogroups];
		int inCursor = 0;
		int outCursor = 0;
		try {
			for(int i=0;i<fullGroups;i++){
				int ch0 = base64toInt(data.charAt(inCursor++));
				int ch1 = base64toInt(data.charAt(inCursor++));
				int ch2 = base64toInt(data.charAt(inCursor++));
				int ch3 = base64toInt(data.charAt(inCursor++));
				result[outCursor++] = (byte) ((ch0<<2)|(ch1>>4));
				result[outCursor++] = (byte) ((ch1<<4)|(ch2>>2));
				result[outCursor++] = (byte) ((ch2<<6)|ch3);
			}
			if(nogroups!=0){
				int ch0 = base64toInt(data.charAt(inCursor++));
				int ch1 = base64toInt(data.charAt(inCursor++));
				result[outCursor++] = (byte) ((ch0<<2)|(ch1>>4));
				if(nogroups==1){
					int ch2 = base64toInt(data.charAt(inCursor++));
					result[outCursor++] = (byte) ((ch1<<4)|(ch2>>2));
				}
			}
		} catch (Exception e) {
			return null;
		}
		return result;
	}
	
	private static int base64toInt(char c) {
		int result = base64ToInt[c];
		if(result<0){
			throw new RuntimeException();
		}
		return result;
	}
	
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值