package com.cf.imes.framework.common.util.encrypt;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * AES对称加密工具
 *
 * @author Gqr
 * @since 2024/8/23 16:38
 */
@Slf4j
public class AesUtils {

    private static final String AES_ALG = "AES";

    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/GCM/NoPadding";


    /**
     * 解密
     *
     * @param content
     * @param aesKey
     * @return
     * @throws Exception
     */
    public static String decrypt(String base64Content, String aesKey) {
        try {
            byte[] content = Base64.getDecoder().decode(base64Content);
            GCMParameterSpec params = new GCMParameterSpec(128, content, 0, 12);
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(aesKey), params);
            byte[] decryptData = cipher.doFinal(content, 12, content.length - 12);
            return new String(decryptData);
        } catch (Exception e) {
            log.error("[AesUtils][decrypt]解密失败：{}", e.getMessage(), e);
            // nacos热发布配置，空字符串会导致nacos轮训刷新配置
            return "default";
        }
    }

    /**
     * 生成key
     *
     * @param bytes
     * @return
     * @throws NoSuchAlgorithmException
     */
    private static SecretKey getSecretKey(String key) throws NoSuchAlgorithmException {
        // 生成随机数
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        // 设置随机数种子
        random.setSeed(key.getBytes());

        // aes算法生成器
        KeyGenerator keyGen = KeyGenerator.getInstance(AES_ALG);
        keyGen.init(128, random); // 使用128位的密钥
        SecretKey secretKey = keyGen.generateKey();
        return new SecretKeySpec(secretKey.getEncoded(), AES_ALG);
    }
}
