package com.skr.mdm.handle;

import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import cn.hutool.crypto.symmetric.SM4;
import cn.hutool.json.JSONUtil;
import com.skr.mdm.enums.MdmEncryptEnum;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.util.SmUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.security.SecureRandom;

/**
 * 返回值加密处理
 *
 * @author nfq
 * @date 2022-09-14 16:55
 */
@RestControllerAdvice
public class EncryptResponseHandler implements ResponseBodyAdvice<Object> {

    @Value("${mdm.encrypt}")
    private String mdmEncrypt;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof ResponseResult && MdmEncryptEnum.SM.getMdmEncrypt().equals(mdmEncrypt)) {
            SecureRandom secureRandom = new SecureRandom();
            ResponseResult responseResult = (ResponseResult) body;
            byte[] secretKeyBytes = new byte[16];
            secureRandom.nextBytes(secretKeyBytes);

            // 数据加密
            SM4 sm4 = SmUtil.sm4(secretKeyBytes);
            if (responseResult.getData() != null) {
                responseResult.setData(sm4.encryptHex(JSONUtil.toJsonStr(responseResult.getData())));
            }
            // 密钥
            SM2 sm2 = SmUtils.sm2Crypt();
            responseResult.setSecretKey(sm2.encryptHex(secretKeyBytes, KeyType.PublicKey));
            // 签名
            String sm3 = SmUtil.sm3(JSONUtil.toJsonStr(responseResult.getData()));
            SM2 sm2Sign = SmUtils.sm2Sign();
            responseResult.setSign(sm2Sign.signHex(sm3));
            return responseResult;
        }
        return body;
    }

}
