package com.usky.ems.util;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;

/**
 * AES加密工具类
 * 采用CBC模式，PKCS5填充，密钥和向量相同
 *
 * @author system
 * @since 2024-01-01
 */
public class AesUtil {

    public static String decrypt(String key, byte[] cipherText) {
        try {
            AES aes = new AES(Mode.CBC, Padding.PKCS5Padding,
                    key.getBytes(), key.getBytes());
            return aes.decryptStr(cipherText);
        } catch (Exception e) {
            throw new RuntimeException("密钥错误!");
        }
    }

    public static byte[] encryptEnergyXml(String xml, String key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] uploadKeyBytes = key.getBytes();
        SecretKeySpec secretKeySpec = new SecretKeySpec(uploadKeyBytes, "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(uploadKeyBytes);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        return cipher.doFinal(xml.getBytes(StandardCharsets.UTF_8));
    }

    public static String decryptEnergyXml(byte[] encryptedXml, String key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] uploadKeyBytes = key.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec secretKeySpec = new SecretKeySpec(uploadKeyBytes, "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(uploadKeyBytes);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] decryptedBytes = cipher.doFinal(encryptedXml);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }
}
