package com.ruoyi.yunxin.util;

import java.security.MessageDigest;

public class CheckSumBuilder {

    public static void main(String[] args) {
        String appSecret = "77c09917d2de";
        String curTime = "1707115388876";
        String body = "{\"clientType\":\"IOS\",\"code\":\"200\",\"clientIp\":\"117.153.13.133\",\"accid\":\"33503\",\"sdkVersion\":\"91301\",\"eventType\":\"2\",\"deviceId\":\"2957635E-A852-4EBD-94C7-AA1FFA71551B\",\"timestamp\":\"1707115388795\"}";
        String verifyMD5 = CheckSumBuilder.getMD5(body);
        System.out.println(verifyMD5);
        String verifyChecksum = CheckSumBuilder.getCheckSum(appSecret, verifyMD5, curTime);
        System.out.println(verifyChecksum);
    }


    // 计算并获取CheckSum
    public static String getCheckSum(String appSecret, String bodyMd5, String curTime) {
        return encode("sha1", appSecret + bodyMd5 + curTime);
    }

    // 计算并获取md5值
    public static String getMD5(String requestBody) {
        return encode("md5", requestBody);
    }

    private static String encode(String algorithm, String value) {
        if (value == null) {
            return null;
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            messageDigest.update(value.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();

    }

    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
}
