base64编码和解码

1:Base64存在的意义:

关于base64存在的意义在维基上是这么说的

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.

Base64 encoding schemes are commonly used when there is a need to encode binary data that needs to be stored and transferred over media that is designed to deal with textual data. This is to ensure that the data remains intact without modification during transport. Base64 is commonly used in a number of applications, including email via MIME, and storing complex data in XML.

Base64实际上是对二进制码做分组转换操作

1.每3个8位二进制码位一组,转换为4个6位二进制码为一组(不足6位时地位补0)。3个8位二进制码和4个6位二进制码长度都是24位。

2.对获得的4个6位二进制码补位,每个6位二进制码添加两位高位0,组成4个8位二进制码。

3.将获得的4个8位二进制码转换为4个十进制码。

4.将获得的十进制码转换为Base64字符表中对应的字符。

2:编码过程

1.每3个8位二进制码位一组,转换为4个6位二进制码为一组(不足6位时地位补0)。3个8位二进制码和4个6位二进制码长度都是24位。

2.对获得的4个6位二进制码补位,每个6位二进制码添加两位高位0,组成4个8位二进制码。

3.将获得的4个8位二进制码转换为4个十进制码。

4.将获得的十进制码转换为Base64字符表中对应的字符。

3:实现

JAVA类库中提供了实现类可以实现对Base64的编码和解码,当然也可以根据编码过程自己实现。


import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Base64Test {

	/**
	 * 使用base64解密
	 */
	public static byte[] decrypt(String key) throws Exception {
		return (new BASE64Decoder()).decodeBuffer(key);
	}

	/**
	 * 使用base64加密
	 */
	public static String encrypt(byte[] key) throws Exception {
		return (new BASE64Encoder()).encodeBuffer(key);
	}

	public static void main(String[] args) throws Exception {
		String data = "this is my base64 test";
		System.out.println("original string:" + data);
		
		String after = Base64Test.encrypt(data.getBytes());
		System.out.println("after encryption:" + after);

		byte[] byteArray = Base64Test.decrypt(after);
		System.out.println("after decryption:" + new String(byteArray));
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值