用 java 自带的 java.util.Base64 实现对字符串的加密、解密
加密
String str = "54564654dsf4sd4fsdfsd56f4sd564f56sdf";
String res = Base64.getEncoder().encodeToString(str.getBytes("UTF-8"));
解密
String str = "54564654dsf4sd4fsdfsd56f4sd564f56sdf";
//加密 str
String res = Base64.getEncoder().encodeToString(str.getBytes("UTF-8"));
//解密 res
String restr = new String(Base64.getDecoder().decode(res), "UTF-8");
测试代码
package com.demo.base64;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
public class JdkBase64demo {
public static void main(String[] args) throws UnsupportedEncodingException {
String str = "54564654dsf4sd4fsdfsd56f4sd564f56sdf";
String res = Base64.getEncoder().encodeToString(str.getBytes("UTF-8"));
System.out.println(res);
String restr = new String(Base64.getDecoder().decode(res), "UTF-8");
System.out.println(str);
System.out.println(restr);
}
}
运行结果