Java Base64 加密/解密

來源:互聯網
上載者:User

標籤:unit   .com   類別   編碼   解密   row   ext   test   java 8   

Base64常用來表示字串加密過後的內容,使用Java 程式語言來實作Base64的編碼與解碼功能

1.在Java上做Base64的編碼與解碼,會使用到JDK裡sun.misc套件下的BASE64Encoder和BASE64Decoder這兩個類別,代碼如下

2.Apache Commons Codec有提供Base64的編碼與解碼功能,使用到org.apache.commons.codec.binary套件下的Base64類別

  http://commons.apache.org/proper/commons-codec/download_codec.cgi 下載commons-codec-1.11-bin代碼

3.java 8的java.util套件中,新增了Base64的類別,可以用來處理Base64的編碼與解碼

package com.test;import org.apache.commons.codec.binary.Base64;import org.junit.Test;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;/** * @author ceshi * @Title: JUnitBase64 * @ProjectName ceshi * @Description: TODO * @date 2018/6/1320:59 */public class JUnitBase64 {    @Test    public void test()throws Exception{        //BASE64Encoder        BASE64Encoder encoder = new BASE64Encoder();        BASE64Decoder decoder = new BASE64Decoder();        String text = "你好!";        byte[] textByte = text.getBytes("UTF-8");        //編碼        String encodedText = encoder.encode(textByte);        System.out.println(encoder.encode(text.getBytes("UTF-8"));        //解碼        System.out.println(new String(decoder.decodeBuffer(encodedText), "UTF-8"));        //Apache Commons Codec        Base64 base64 = new Base64();        textByte = text.getBytes("UTF-8");        //編碼        encodedText = base64.encodeToString(textByte);        System.out.println(encodedText);        //解碼        System.out.println(new String(base64.decode(encodedText), "UTF-8"));        //Java 8        Base64.Decoder decoder = Base64.getDecoder();        Base64.Encoder encoder = Base64.getEncoder();        //編碼        encodedText = encoder.encodeToString(textByte);        System.out.println(encodedText);        //解碼        System.out.println(new String(decoder.decode(encodedText), "UTF-8"));    }}

 

Java Base64 加密/解密

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.