package com.lunhan.xxx.common.security;

import com.lunhan.xxx.common.util.StringUtil;

import java.nio.charset.Charset;
import java.util.Base64;

/**
 * Base64工具类
 * @author linliu
 * @date   2019-06-14
 */
public final class Base64Util {
    private Base64Util() {
        throw new IllegalStateException("Utility class");
    }
    private static final String DEFAULT = "utf-8";

    /**
     * base64解码(utf-8编码)
     * @author linliu
     * @date   2019-06-14
     * @param str 密文字符串
     * @return 解码后的明文
     */
    public static String encode(String str) {
        return encode(str, DEFAULT);
    }
    /**
     * base64解码
     * @author linliu
     * @date   2019-06-14
     * @param str 密文字符串
     * @param encoding 编码格式[默认utf-8]
     * @return 解码后的明文
     */
    public static String encode(String str, String encoding) {
        if(StringUtil.isNullOrEmpty(str)) {
            return "";
        }
        if(StringUtil.isNullOrEmpty(encoding)) {
            encoding = DEFAULT;
        }
        byte[] bytes = str.getBytes(Charset.forName(encoding));
        return Base64.getEncoder().encodeToString(bytes);
    }
    /**
     * base64解码(utf-8编码)
     * @author linliu
     * @date   2019-06-14
     * @param str 密文字符串
     * @return 解码后的明文
     */
    public static String decode(String str) {
        return decode(str, DEFAULT);
    }
    /**
     * base64解码
     * @author linliu
     * @date   2019-06-14
     * @param str 密文字符串
     * @param encoding 编码格式[默认utf-8]
     * @return 解码后的明文
     */
    public static String decode(String str, String encoding) {
        if(StringUtil.isNullOrEmpty(str)) {
            return "";
        }
        if(StringUtil.isNullOrEmpty(encoding)) {
            encoding = DEFAULT;
        }
        byte[] bytes = Base64.getDecoder().decode(str);
        return new String(bytes, Charset.forName(encoding));
    }

    /**
     * 二进制流转成base64字符串
     * @param buffer 二进制数组
     * @return 编码后的base64字符串
     */
    public static String encodeStream(final byte[] buffer) {
        return Base64.getEncoder().encodeToString(buffer);
    }

    /**
     * 二进制流转成base64流
     * @param buffer 二进制数组
     * @return 编码后的base64流
     */
    public static byte[] encodeToStream(final byte[] buffer) {
        return Base64.getEncoder().encode(buffer);
    }

    /**
     * base64字符串转成二进制流
     * @param str 密文字符串
     * @return 解码后的文件流
     */
    public static byte[] decodeToStream(String str) {
        try {
            return Base64.getDecoder().decode(str);
        } catch (Exception e) {
            return new byte[0];
        }
    }

    /**
     * base64字符串转成二进制流
     * @param buffer 密文流
     * @return 解码后的文件流
     */
    public static byte[] decodeToStream(final byte[] buffer) {
        try {
            return Base64.getDecoder().decode(buffer);
        } catch (Exception e) {
            return new byte[0];
        }
    }
}