Base64编码介绍
BASE64 编码是一种常用的字符编码,Base64编码本质上是一种将二进制数据转成文本数据的方案。
但base64不是安全领域下的加密解密算法。能起到安全作用的效果很差,而且很容易破解,他核心作用应该是传输数据的正确性,有些网关或系统只能使用ASCII字符。
Base64就是用来将非ASCII字符的数据转换成ASCII字符的一种方法,而且base64特别适合在http,mime协议下快速传输数据。
使用场景
1.对数据传输过程中不可见字符的处理;
2.将图片二进制转为Base64编码嵌入网页,可有效减少HTTP请求图片带来性能提升;
Java对于Base64编码的支持,
这里只讲原生JDK支持,足够你用的,别搞些第三方的:
package com.dylan.security;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.IOException;
import java.util.Base64;
/**
* Base64编码测试类
*
* @author xusucheng
* @create 2017-12-19
**/
public class TestBase64 {
public static final String toEncode="Hello Base64!";
/**
* jdk8以前
* @throws IOException
*/
public static void TestBase64Old() throws IOException {
//编码
BASE64Encoder encoder=new BASE64Encoder();
String encoded = encoder.encode(toEncode.getBytes());
System.out.println("编码后:"+encoded);
//解码
BASE64Decoder decoder=new BASE64Decoder();
byte[] decoded = decoder.decodeBuffer(encoded);
System.out.println("解码后:"+new String(decoded));
}
/**
* jdk1.8后
*/
public static void TestBase64New(){
//编码
String encoded = Base64.getEncoder().encodeToString(toEncode.getBytes());
System.out.println("编码后:"+encoded);
//解码
byte[] decoded = Base64.getDecoder().decode(encoded);
System.out.println("解码后:"+new String(decoded));
}
public static void main(String[] args) throws IOException {
System.out.println("Before JDK1.8:");
TestBase64Old();
System.out.println("After JDK1.8:");
TestBase64New();
}
}
输出:
Before JDK1.8:
编码后:SGVsbG8gQmFzZTY0IQ==
解码后:Hello Base64!
From JDK1.8:
加密后:SGVsbG8gQmFzZTY0IQ==
解码后:Hello Base64!