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

原文地址:https://www.cnblogs.com/h-wei/p/10565717.html