package com.zcloud.common.ddos;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.SortedMap;

@Slf4j
@UtilityClass
public class SignUtil {

    private final String secret = "ab934679413c0fff22bb846365e14e00d8c504294760d21d660490bd43a69a90";
    /**
     * 验证签名
     * 验证算法：把timestamp + JsonUtil.object2Json(SortedMap)合成字符串，然后MD5
     */
    @SneakyThrows
    public  boolean verifySign(SortedMap<String, Object> map, RequestHeader requestHeader) {
        StringBuffer params = new StringBuffer();
        params.append(requestHeader.getTimestamp()).append(JSON.toJSONString(map)).append(secret);
        return verifySign(params, requestHeader);
    }

    /**
     * 验证签名
     */
    public boolean verifySign(StringBuffer params, RequestHeader requestHeader) {
        log.debug("客户端签名: {}", requestHeader.getSign());
        if (StringUtils.isEmpty(params.toString())) {
            return false;
        }
        log.info("客户端上传内容: {}", params);
        String paramsSign = new Md5Hash(params.toString()).toString();
        log.info("客户端上传内容加密后的签名结果: {}", paramsSign);
        return requestHeader.getSign().equals(paramsSign);
    }

    public static void main(String[] args) {
        System.out.println(new Sha256Hash("兔优素材库", "zcloud88888") );
        System.out.println(new Md5Hash("1699596698610{\"inputCode\":\"1\",\"password\":\"1\",\"phone\":\"13111111111\",\"verification\":\"\"}ab934679413c0fff22bb846365e14e00d8c504294760d21d660490bd43a69a90"));
    }

}
