base64编码和解码

来源:互联网 发布:专业网站美工 编辑:程序博客网 时间:2024/05/21 11:38

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));}}



0 0