Java Base64 加密/解密

时间:2025-03-07 10:33:32

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