java中Base64編碼與解碼

java中Base64編碼與解碼

一、Base64簡介

Base64是一種編碼與解碼方式,用於將二進制數據編碼爲64個可打印字符,或者相反操作。

二、知識點

2.1 Base64字符

Base64有64個可打印字符,包括:A-Z,a-z,0-9,+,/,它們的編碼分別從0到63。

2.2 Base64實現

Base64內部實現是:將二進制流以6位分組,然後每個分組高位補2個0(計算機是8位存數),這樣每個組值就是在64以內,然後轉爲對應的編碼。

三、實例

3.1 jdk原生實現

實現方式一,藉助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

3.2 commons-codec包實現

實現方式二,藉助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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章