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("需要解密的数据");

  • 相关阅读:
    MySQL锁概述
    MYSQL删除重复记录
    SPRING事务控制
    性能测试中如何确定并发用户数
    Jsoup操作
    linux根据端口号查询进程
    linux下解压jar文件
    开发阶段的logback.xml
    栈--getMin(leetcode 155)
    git "fatal: The remote end hung up unexpectedly"
  • 原文地址:https://www.cnblogs.com/h-wei/p/10565717.html
Copyright © 2011-2022 走看看