1.使用jdk自带包解码编码:
package com.cl;
import java.io.IOException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class JdkBase64 {
private static String src="imooc security base64";
public static void main(String[] args) {
base64();
}
public static void base64(){
BASE64Encoder encoder=new BASE64Encoder();
String dst=encoder.encode(src.getBytes());
System.out.println("encode:"+dst);
BASE64Decoder decoder=new BASE64Decoder();
try {
System.out.println(new String(decoder.decodeBuffer(dst)));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
若遇到不能引入相关BASE64Decoder和BASE64Decoder包的话,可以用如下方法解决:
https://blog.youkuaiyun.com/erlian1992/article/details/79518416
2.使用Bouncy Caslte提供的包Base64解密加密:需要引入如下的包
以上两个包需要匹配jdk版本使用:具体可以在http://bouncycastle.org/latest_releases.html里查看和下载合适版本
package com.cl;
import org.bouncycastle.util.encoders.Base64;
public class BCBase64 {
private static String src="imooc security base64";
public static void main(String[] args) {
BouncyCastleBase64();
}
public static void BouncyCastleBase64(){
byte[] encode=Base64.encode(src.getBytes());
System.out.println("encode:"+new String(encode));
byte[] decode=Base64.decode(encode);
System.out.println("decode:"+new String(decode));
}
}
3使用Commons Codec的方法Base64解密加密:需要下载如下
以上包并不需要与jdk版本对应。
package com.cl;
import org.apache.commons.codec.binary.Base64;
public class CCBase64 {
private static String src="imooc security base64";
public static void main(String[] args) {
CommonsCodecBase64();
}
public static void CommonsCodecBase64(){
byte[] encode=Base64.encodeBase64(src.getBytes());
System.out.println("encode:"+new String(encode));
byte[] decode=Base64.decodeBase64(encode);
System.out.println("decode:"+new String(decode));
}
}
4三个的运行结果一致: