Base64的编码解码

  • Maven
<dependency>
     <groupId>org.apache.tomcat</groupId>
     <artifactId>tomcat-util</artifactId>
     <version>10.0.10</version>
</dependency>
  • Base64的编码解码
import com.alibaba.fastjson.JSONObject;
import org.apache.tomcat.util.codec.binary.Base64;
import java.io.UnsupportedEncodingException;

public class EDbase64 {
    /**
     * 编码
     */
    public static String encodeBase64(String encodeStr) {
        try {
            encodeStr = new String(Base64.encodeBase64(encodeStr.getBytes("UTF-8")));
            return encodeStr;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解码
     */
    public static String decodeBase64(String decodeStr) {
        try {
            decodeStr = new String(Base64.decodeBase64(decodeStr.getBytes()),"UTF-8");
            return decodeStr;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        JSONObject json = new JSONObject();
        json.put("a","123");
        json.put("b","qaz");
        json.put("c","测试");

        String encode = EDbase64.encodeBase64(JSONObject.toJSONString(json));
        System.out.println("加密:" + encode);

        String decode = EDbase64.decodeBase64(encode);
        System.out.println("解密:" + decode);
    }
}

  

posted on 2021-08-26 18:05  陌生街中吹起褪色故梦  阅读(477)  评论(0编辑  收藏  举报