zoukankan      html  css  js  c++  java
  • Base 64 加密、解密

    1、写一个公共类

    package com.boyutec.oss.sys.utils;


    import java.io.UnsupportedEncodingException;

    import java.util.regex.Pattern;

    import sun.misc.*;

    public class Base64 {
    // 加密
    @SuppressWarnings("restriction")
    public static String getBase64(String str) {
    byte[] b = null;
    String s = null;
    try {
    b = str.getBytes("utf-8");
    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    }
    if (b != null) {
    s = new BASE64Encoder().encode(b);
    }
    return s.replaceAll("[ ]*", "");
    }

    // 解密
    @SuppressWarnings("restriction")
    public static String getFromBase64(String s) {
    byte[] b = null;
    String result = null;
    if (null == s) {
    return s;
    }
    boolean base64 = isBase64(s.replaceAll("[ ]*", ""));
    if (base64) {
    if (s != null) {
    BASE64Decoder decoder = new BASE64Decoder();
    try {
    b = decoder.decodeBuffer(s.replaceAll("[ ]*", ""));
    result = new String(b, "utf-8");
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    } else {
    result = s;
    }
    return result;
    }

    private static boolean isBase64(String str) {
    String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
    return Pattern.matches(base64Pattern, str);
    }
    public static void main(String[] args) {
    System.out.println(getFromBase64("6ZiF"));
    }
    }

    2、可以直接调用:1)Base64.getBase64("需要加密的数据"); 2) Base64.getFromBase64("需要解密的数据");

  • 相关阅读:
    第一次用python 写的简单爬虫 记录在自己的博客
    【转】使用notepad运行python
    Android Tools&Cmd
    箴言
    无问西东
    Unity存储路径
    手机屏幕亮度设定
    Go Lang
    iOS .tbd
    Prime31
  • 原文地址:https://www.cnblogs.com/h-wei/p/10565717.html
Copyright © 2011-2022 走看看