package com.changhu.common.utils;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
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;


/**
 * @author 20252
 * @createTime 2024/8/20 下午4:57
 * @desc rsa加密工具类
 */
@Slf4j
public class RsaUtil {

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

    /**
     * rsa实例
     */
    private static final RSA rsa = new RSA(setting.getStr("privateKey"), setting.getStr("publicKey"));


    /**
     * 通过公钥进行加密
     *
     * @param text 需要加密的密码
     * @return 加密的结果
     */
    public static String encipher(String text) {
        try {
            return rsa.encryptHex(text, KeyType.PublicKey);
        } catch (Exception e) {
            log.error("加密失败: {}", e.getMessage());
            throw new MessageException(ResultCode.ENCIPHER_ERROR);
        }
    }

    /**
     * 通过私钥解密
     *
     * @param encryptedString 加密后的字符串
     * @return 解密后的结果
     */
    public static String decrypt(String encryptedString) {
        try {
            return rsa.decryptStr(encryptedString, KeyType.PrivateKey);
        } catch (Exception e) {
            log.error("解码失败: {}", e.getMessage());
            throw new MessageException(ResultCode.DECRYPT_ERROR);
        }
    }

}
