/*
 * Copyright (c) 2023 codvision.com All Rights Reserved.
 */

package com.codvision.webapi.common;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.extra.spring.SpringUtil;
import com.codvision.commoncore.exception.BusinessException;
import com.codvision.webapi.config.EncryptProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 加密工具类
 *
 * @author lingee
 * @date 2023/8/3
 */
@Slf4j
public class EncryptUtil {

    public static String encoderBody(Object data) {
        EncryptProperties encryptProperties = SpringUtil.getBean(EncryptProperties.class);
        ObjectMapper objectMapper = SpringUtil.getBean(ObjectMapper.class);

        try {
            byte[] bytes = objectMapper.writeValueAsBytes(data);

            AES aes = new AES(Mode.CBC, Padding.ZeroPadding, new SecretKeySpec(encryptProperties.getSecretKey().getBytes(), "AES"),
                    new IvParameterSpec(encryptProperties.getSecretKey().getBytes()));
            return aes.encryptBase64(bytes);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException(30001, "远程调用接口加密失败");
        }
    }

    public static byte[] decoderBody(String bodyString) {
        EncryptProperties encryptProperties = SpringUtil.getBean(EncryptProperties.class);

        AES aes = new AES(Mode.CBC, Padding.ZeroPadding, new SecretKeySpec(encryptProperties.getSecretKey().getBytes(), "AES"),
                new IvParameterSpec(encryptProperties.getSecretKey().getBytes()));

        byte[] decryptedBody;
        try {
            decryptedBody = aes.decrypt(bodyString);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException(30001, "远程调用接口解密失败");
        }
        return decryptedBody;
    }
}
