Base64 编码介绍:Base64是可以将任意的字节数组数据,通过算法,生成只有(大小写英文、数字、+、/)(一共64个字符)内容表示的字符串数据。
Base64编码索引表
除了JDK实现Base64加解密算法以外还有bouncy castle 和commons-codec
下面针对这三种方式分别给出例子:
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder; // 如果出现不能引入的情况,查看使用的jdk是否是工具的自带的,如果是的,使用自己安装的jdk
import sun.misc.BASE64Encoder;
public class Test {
public static String SRC ="这是我的内容";
public static void main(String[] args) {
// jdkBase64();
// commonsCodeBase64();
bouncyCastBase64();
}
/**
* 通过jdk自带的base64编码
*/
public static void jdkBase64(){
try {
BASE64Encoder encoder = new BASE64Encoder();
String encode = encoder.encode(SRC.getBytes());
System.out.println(encode);
BASE64Decoder decoder = new BASE64Decoder();
byte[] decodeBytes = decoder.decodeBuffer(encode);
System.out.println(new String(decodeBytes));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* commons codes方式
*/
public static void commonsCodeBase64(){
try {
byte[] encode = Base64.encodeBase64(SRC.getBytes());
System.out.println(new String(encode));
byte[] decode = Base64.decodeBase64(encode);
System.out.println(new String(decode));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* bouncyCast 方式
*/
public static void bouncyCastBase64(){
try {
byte[] encode = org.bouncycastle.util.encoders.Base64.encode(SRC.getBytes());
System.err.println(new String(encode));
byte[] decode = org.bouncycastle.util.encoders.Base64.decode(encode);
System.out.println(new String(decode));
} catch (Exception e) {
e.printStackTrace();
}
}
}
base64不是加密技术,只能算是编码,因为加密结果都是由上面表格一一对应的,所以有编码后的内容是能够得到编码前的内容的。