package com.yuchen.saas.park.service.util;

import org.nest.springwrap.core.tool.utils.Func;

import java.util.Base64;
import java.util.regex.Pattern;

/**
 * @author 刘通
 * @version 1.0
 * @date 2021/3/2 16:46
 */
@Deprecated
public class StrBase64Utils {
    /**
     * 加密
     * @param str
     * @return
     */
    public static String encodeBASE64(String str) {
        if(Func.isEmpty(str)) {
            return str;
        }
        String returnStr = "";
        try {
            returnStr = Base64.getEncoder().encodeToString(str.getBytes());
        } catch(Exception e) {
            e.printStackTrace();
        }
        return returnStr;
    }
    /**
     * 解密
     * @param str
     * @return
     */
    public static String decoderBASE64(String str) {
        if(Func.isEmpty(str)) {
            return str;
        }
        String returnStr = "";
        if(isBase64(str)) {
            try {
                byte[] decoded = Base64.getDecoder().decode(str);
                returnStr = new String(decoded);
            } catch(Exception e) {
                e.printStackTrace();
            }
        } else {
            return str;
        }
        return returnStr;
    }

    /**
     * 判断字符串是否为 Base64
     * @param str
     * @return
     */
    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);
    }
}
