package com.lutao.cloud.collect.utils;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import com.lutao.cloud.collect.dto.DataAddDTO;
import com.lutao.entity.AppInfo;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

@Slf4j
public class CheckUtil {



    public static final String appKey = "abc";
    public static final String appSecret = "def";
    public static final String aeskey = "wehyy%kwehdwdese";

    /**
     * 校验sign
     *
     * @param dataAdd 数据添加
     * @return boolean
     */
    public static boolean checkSign(AppInfo appInfo,DataAddDTO dataAdd) {

        StringBuffer sb = new StringBuffer();
        sb.append(appInfo.getAppKey()).append(appInfo.getAppSecret()).append(dataAdd.getTs()).append(dataAdd.getRequestId())
                .append(dataAdd.getCommand()).append(dataAdd.getResource()).append(dataAdd.getData());
        log.info("signStr:{}", sb.toString());
        // 获取sign
        String sign = SHAEncrypt.SHA256(sb.toString());
        log.info("sign:{}", sign);
        log.info("usersign:{}", dataAdd.getSign());
        return sign.equals(dataAdd.getSign());
    }

    /**
     * 校验解密后的data是否是json格式
     *
     * @param data 数据
     * @return {@link String}
     */
    public static String decrypData(AppInfo appInfo, String data) {
        if (appInfo == null){
            return null;
        }
        AES aes = new AES(Mode.CFB, Padding.NoPadding,
                new SecretKeySpec(appInfo.getClientSecret().getBytes(StandardCharsets.UTF_8), "AES"),
                new IvParameterSpec(appInfo.getClientSecret().getBytes(StandardCharsets.UTF_8)));
        return aes.decryptStr(data);
        //return data;
    }

}
