关闭

Base64使用案例

3172人阅读 评论(0) 收藏 举报
分类:

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

Base64编码可用于在HTTP环境下传递较长的标识信息以及二进制数据(例如图片文件、PDF文件等等)。

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

['A', 'B', 'C', ... 'a', 'b', 'c', ... '0', '1', ... '+', '/']
也就是52个大小写字母加上10个阿拉伯数字再加上两个字符‘+’、‘/’。字符索引为0~63。

然后,对二进制数据进行处理,每3个字节划为一组,一共是3x8=24bit,再将24bit划为4组,每组正好6个bit(可表示2的6次方、即64个数):

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

所以,Base64编码会把3字节的二进制数据编码为4字节的文本数据,长度增加33%。

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

示例

使用的工具包为commons-codec-1.3.jar。

Base64Util:

package com.zzj.base64;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;

public class Base64Util {
	
	/**
	 * 编码字符串
	 * @param source
	 * @return
	 */
	public static String encode(String source){
		try {
			byte[] sourceBs = source.getBytes("UTF-8");
			byte[] targetBs = Base64.encodeBase64(sourceBs);
			return new String(targetBs, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 编码文件
	 * @param source
	 * @return
	 * @throws IOException
	 */
	public static String encode(File source) throws IOException {
		byte[] sourceBs = FileUtils.readFileToByteArray(source);
		byte[] targetBs = Base64.encodeBase64(sourceBs);
		return new String(targetBs, "UTF-8");
	}
	
	/**
	 * 解码字符串
	 * @param target
	 * @return
	 */
	public static String decode(String target){
		try {
			byte[] targetBs = target.getBytes("UTF-8");
			byte[] sourceBs = Base64.decodeBase64(targetBs);
			return new String(sourceBs, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 解码文件
	 * @param target
	 * @param file
	 * @throws Exception
	 */
	public static void decode(String target, File file) throws Exception {
		byte[] targetBs = target.getBytes("UTF-8");
		byte[] sourceBs = Base64.decodeBase64(targetBs);
		FileUtils.writeByteArrayToFile(file, sourceBs);
	}
	
	
	private Base64Util() {
	}
}
测试App:
package com.zzj.base64;

import java.io.File;
import java.io.IOException;

public class App {
	public static void main(String[] args) throws Exception {
		testStr();
		testFile();
	}

	/**
	 * 字符串编码和解码
	 */
	private static void testStr() {
		String source = "我是一个兵";
		
		String target = Base64Util.encode(source);
		System.out.println("编码:" + target);
		
		source = Base64Util.decode(target);
		System.out.println("解码:" + source);
	}
	
	/**
	 * 文件编码和解码
	 * @throws IOException
	 * @throws Exception
	 */
	private static void testFile() throws IOException, Exception {
		File source = new File(App.class.getResource("logo.gif").getPath());
		
		String target = Base64Util.encode(source);
		System.out.println("编码:" + target);
		
		File targetFile = new File("C:\\logo.gif");
		Base64Util.decode(target, targetFile);
		System.out.println("解码:" + targetFile.toString());
	}
}
结果:
编码:5oiR5piv5LiA5Liq5YW1
解码:我是一个兵
编码:R0lGODlh1QApAPcAAAEBAQwMDBQUFBwcHCMjIywsLDQ0NDw8PENDQ0tLS1RUVFxcXGNjY2tra3Nzc3p6ev8BAP8MAP8UAP8bAP8iAP8rAP8hCP80AP87AP9DAP9MAP9UAP9dAv9VCP9dC/9XHf9iAv9qAv9qCv9zA/94Av9wCv98Cf9iEP9qFP92Ev99FP9wGf99GP9UNv9kKP96Jv9vP/9zMv9pUP9/a/+CBP+GDv+NDf+UAP+YAP+HFv+LEf+GGv+LHv+QEv+XG/+bGv+jBv+rAf+sDP+1BP+/DP+rE/+hGv+qHP+7EP+zHv+6Hf+NIv+GLv+UJP+cLf+KNP+NOP+fMf+YPv+kJ/+tJf+jLf+tKv+zLv++LP+rMv+jO/+qPf+zMv+/Ov/BG//BJP/AKf/UI//DNv/KNv/EPP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gBk24EdWicZwAfw3heWKHh7uIduoQCgAweOqgdtMyWgmQCe4ojvLoKPT/SIsHwQAoF2AG4Xm3MQAIZxAA0GyjhUgEoHCQI3MNUAACICvFyJCJWISklgKXoga9QA2SsCkUwAUF9xC6RAETEAJ+IAk8oEYgYAsfJh4C8Q2ZoFtLoQlE4S7VoV2ZwFTOgCxF5QAyo4EqlF+CwQwKQiYHcQ5o4l5D4xdUcj+H5wy3oxQHARkMoAm0gw46wR96+XyZYF4WsQ1ZcAEr8AiuB2W44FwgcAlwwQcYkAFI1w3pcAsrIgFT8HTqVptoZg5/cANqcAtdtg2O4ARKwGkN8Qo0cAJ04G8GERwvMAKLYJvOiWaSgASPQIUO0Qt8cAcHSAxKsAWoAG4C0QtvgAS+N/Cc5PlkdyALR1YJGeZoZVAIW+cQ2/AIf6Bl5VmfNpYLv3YR5cAQB0ELj8CfFcELqGafBPphAQEAOw==
解码:C:\logo.gif

问题

以下内容摘自网络

标准的Base64并不适合直接放在URL里传输,因为URL编码器会把标准Base64中的“/”和“+”字符变为形如“%XX”的形式,而这些“%”号在存入数据库时还需要再进行转换,因为ANSI SQL中已将“%”号用作通配符。

为解决此问题,可采用一种用于URL的改进Base64编码,它在末尾填充'='号,并将标准Base64中的“+”和“/”分别改成了“-”和“_”,这样就免去了在URL编解码和数据库存储时所要作的转换,避免了编码信息长度在此过程中的增加,并统一了数据库、表单等处对象标识符的格式。

另有一种用于正则表达式的改进Base64变种,它将“+”和“/”改成了“!”和“-”,因为“+”,“*”以及前面在IRCu中用到的“[”和“]”在正则表达式中都可能具有特殊含义。

此外还有一些变种,它们将“+/”改为“_-”或“._”(用作编程语言中的标识符名称)或“.-”(用于XML中的Nmtoken)甚至“_:”(用于XML中的Name)。



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1214426次
    • 积分:11726
    • 等级:
    • 排名:第1453名
    • 原创:293篇
    • 转载:142篇
    • 译文:1篇
    • 评论:108条
    最新评论