package com.changhu.common.utils;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.setting.Setting;
import cn.hutool.setting.SettingUtil;
import com.changhu.common.enums.ResultCode;
import com.changhu.common.exception.MessageException;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * author: luozhun
 * desc: 加密解密工具
 * createTime: 2023/8/19 12:21
 */
@Slf4j
public class AesUtil {

    /**
     * 配置文件
     */
    private static final Setting setting = SettingUtil.get("aes");

    /**
     * AES实例
     */
    private static final AES aes = new AES(
            Mode.CBC,
            Padding.PKCS5Padding,
            setting.getStr("secretKey").getBytes(StandardCharsets.UTF_8),
            setting.getStr("secretIv").getBytes(StandardCharsets.UTF_8)
    );

    /**
     * 加密 明文 -> 密文
     *
     * @param text 加密字符串
     * @return 加密的结果
     */
    public static String encrypt(String text) {
        try {
            return aes.encryptHex(text);
        } catch (Exception e) {
            log.error("加密失败: {}", e.getMessage());
            throw new MessageException(ResultCode.ENCIPHER_ERROR);
        }
    }

    /**
     * 解密: 密文 -> 明文
     */
    public static String decrypt(String cipherString) {
        try {
            return aes.decryptStr(cipherString);
        } catch (Exception e) {
            log.error("解密失败: {}", e.getMessage());
            throw new MessageException(ResultCode.DECRYPT_ERROR);
        }
    }

}
