Base64一种把二进制数据用文本表示的编码算法。例如
中有3个字节{\xe4, \xb8, \xad},一共是24位,每6位分组,变成4个字节{39, 0b, 22, 2d},最终结果位5Lit。
如果长度不是3的整数倍:
Base64编码:
应用
public class SplitString {
public static void main(String[] args) throws Exception {
String original = "Hello\u00ff编码测试";
byte[] bs = original.getBytes("UTF-8");
//1.8以后不推荐使用
String b64_1 = java.util.Base64.getEncoder().encodeToString(bs);
System.out.println("java.util.Base64编码:"+b64_1);
String ori_1 = new String(java.util.Base64.getDecoder().decode(b64_1),"UTF-8");
System.out.println("java.util.Base64解码:"+ori_1);
System.out.println();
String b64_2=com.sun.org.apache.xml.internal.security.utils.Base64.encode(bs);
System.out.println("com.sun.org.apache.xml.internal.security.utils.Base64编码:"+b64_2);
String ori_2 = new String(com.sun.org.apache.xml.internal.security.utils.Base64.decode(b64_2),"UTF-8");
System.out.println("com.sun.org.apache.xml.internal.security.utils.Base64解码:"+ori_2);
System.out.println();
String b64_3 = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.encode(bs);
System.out.println("com.sun.org.apache.xerces.internal.impl.dv.util.Base64编码:"+b64_3);
String ori_3 = new String(com.sun.org.apache.xerces.internal.impl.dv.util.Base64.decode(b64_3),"UTF-8");
System.out.println("com.sun.org.apache.xerces.internal.impl.dv.util.Base64解码:"+ori_3);
}
}
public class SplitString {
public static void main(String[] args) throws Exception {
String original = "Hello\u00ff编码测试";
byte[] bs = original.getBytes("UTF-8");
//1.8以后不推荐使用
String b64_1 = java.util.Base64.getEncoder().withoutPadding().encodeToString(bs);
System.out.println("java.util.Base64编码:"+b64_1);
String ori_1 = new String(java.util.Base64.getDecoder().decode(b64_1),"UTF-8");
System.out.println("java.util.Base64解码:"+ori_1);
System.out.println();
}
}
标准的Base64编码在URL中会引起冲突。如+,/。通过Base64的URL编码可以将+替换为-,将/替换为_来避免冲突
public class SplitString {
public static void main(String[] args) throws Exception {
String original = "Hello\u00ff编码测试";
byte[] bs = original.getBytes("UTF-8");
//1.8以后不推荐使用
String b64_1 = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(bs);
System.out.println("java.util.Base64编码:"+b64_1);
String ori_1 = new String(java.util.Base64.getUrlDecoder().decode(b64_1),"UTF-8");
System.out.println("java.util.Base64解码:"+ori_1);
System.out.println();
}
}
廖雪峰Java10加密与安全-2加密算法-2Base64编码
原文:https://www.cnblogs.com/csj2018/p/10828146.html