You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hai-oil-server/service/src/main/java/com/hfkj/common/Base64Util.java

42 lines
1.3 KiB

package com.hfkj.common;
import java.util.Base64;
public class Base64Util {
/**
* @param data
* @return str
* @throws Exception
*/
public static String encode(String data) throws Exception{
// String encodeBase64 = new BASE64Encoder().encode(data.getBytes("utf-8"));
String encodeBase64 = Base64.getEncoder().encodeToString(data.getBytes("utf-8"));
String safeBase64Str = encodeBase64.replace('+', '-');
safeBase64Str = safeBase64Str.replace('/', '_');
safeBase64Str = safeBase64Str.replaceAll("=", "");
return safeBase64Str.replaceAll("\\s*", "");
}
/**
* @param safeBase64Str
* @return str
* @throws Exception
*/
public static String decode(final String safeBase64Str) throws Exception{
String base64Str = safeBase64Str.replace('-', '+');
base64Str = base64Str.replace('_', '/');
int mod4 = base64Str.length() % 4;
if(mod4 > 0){
base64Str += "====".substring(mod4);
}
// byte[] ret = new BASE64Decoder().decodeBuffer(base64Str);
byte[] ret = Base64.getDecoder().decode(base64Str);
return new String(ret, "utf-8");
}
public static void main(String[] args) throws Exception {
System.out.println(encode("abcd1234"));
System.out.println(decode("YWJjZDEyMzQ"));
}
}