java中Base64编码与解码

来源:互联网 发布:tensorflow 视频教程 编辑:程序博客网 时间:2024/05/17 04:07

一、Base64简介

Base64是一种编码与解码方式,用于将二进制数据编码为64个可打印字符,或者相反操作。

这64个可打印字符包括:A-Z,a-z,0-9,+,/,它们的编码分别从0到63。

Base64内部实现是:将二进制流以6位分组,然后每个分组高位补2个0(计算机是8位存数),

这样每个组值就是在64以内,然后转为对应的编码。

二、实例

1、实现方式一,借助jdk自身的BASE64Encoder和BASE64Decoder

public class Base64Main {    public static void main(String[] args) throws Exception {        String source = "study hard and make progress everyday";        System.out.println("source : "+ source);        String result = base64Encode(source.getBytes("utf8"));  //编码        System.out.println("encode result : " + result);        String rawSource = new String(base64Decode(result),"utf8");  //解码        System.out.println("decode result : "+ rawSource);    }    //编码    static String base64Encode(byte[] source) {        BASE64Encoder encoder = new BASE64Encoder();        return encoder.encode(source);    }    //解码    static byte[] base64Decode(String source){        try {            BASE64Decoder decoder = new BASE64Decoder();            return decoder.decodeBuffer(source);        } catch (IOException e) {        }        return null;    }}
运行结果:

source : study hard and make progress everyday
encode result : c3R1ZHkgaGFyZCBhbmQgbWFrZSBwcm9ncmVzcyBldmVyeWRheQ==
decode result : study hard and make progress everyday

2、实现方式二,借助commons-codec包

添加maven依赖:

<dependency>    <groupId>commons-codec</groupId>    <artifactId>commons-codec</artifactId>    <version>1.10</version></dependency>
代码:

public class Base64FromCommonsMain {    public static void main(String[] args) throws Exception {        String source = "study hard and make progress everyday";        System.out.println("source : "+ source);        String result = Base64.encodeBase64String(source.getBytes("utf8")); //编码        System.out.println("encode result : " + result);        String rawSource = new String(Base64.decodeBase64(result),"utf8"); //解码        System.out.println("decode result : "+ rawSource);    }}
运行结果:

source : study hard and make progress everyday
encode result : c3R1ZHkgaGFyZCBhbmQgbWFrZSBwcm9ncmVzcyBldmVyeWRheQ==
decode result : study hard and make progress everyday