package com.koobietech.eas.common.utils;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.koobietech.eas.common.exception.EasException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author lc
 */
@Component
public class PasswordManager {


    @Value("${eas.password-sign-key}")
    String passwordSignKey;

    public String decryptPassword(String data) {
        SecureUtil.disableBouncyCastle();
        AES aes = new AES(passwordSignKey.getBytes(StandardCharsets.UTF_8));
        String decryptStr;
        String decryptPassword;
        try {
            decryptStr = aes.decryptStr(data);
            decryptPassword = decryptStr.substring(13);
        } catch (Exception e) {
            throw new EasException("AES解密错误", e);
        }
        return decryptPassword;
    }

    public String archiveEncryptPassword(String data) {
        SecureUtil.disableBouncyCastle();
        AES aes = new AES(passwordSignKey.getBytes(StandardCharsets.UTF_8));
        String encryptStr;
        try {
            encryptStr = aes.encryptHex(data);
        } catch (Exception e) {
            throw new EasException("AES加密错误", e);
        }
        return encryptStr;
    }

    public String archiveDecryptPassword(String encryptedData) {
        SecureUtil.disableBouncyCastle();
        AES aes = new AES(passwordSignKey.getBytes(StandardCharsets.UTF_8));
        String decryptedStr;
        try {
            decryptedStr = aes.decryptStr(encryptedData);
        } catch (Exception e) {
            throw new EasException("AES解密错误", e);
        }
        return decryptedStr;
    }
}
