package com.zanxiang.game.module.sdk.util;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;

/**
 * @author : lingfeng
 * @time : 2022-09-23
 * @description : 签名算法工具类
 */
public class SignUtil {

    /**
     * MD5加密
     */
    private static final String SIGN_MD5 = "MD5";

    /**
     * HMACSHA256加密
     */
    private static final String SIGN_HMACSHA256 = "HMACSHA256";

    /**
     * MD5加密
     */
    private static final String SIGN_SHA1 = "SHA-1";

    /**
     * MD5加密
     *
     * @param data 待处理数据
     * @return MD5结果
     */
    public static String MD5(String data) throws Exception {
        java.security.MessageDigest md = MessageDigest.getInstance(SIGN_MD5);
        byte[] array = md.digest(data.getBytes(StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3);
        }
        return sb.toString().toUpperCase();
    }

    /**
     * HMACSHA256加密
     *
     * @param data 待处理数据
     * @param key  密钥
     * @return 加密结果
     * @throws Exception : 异常
     */
    public static String HMACSHA256(String data, String key) throws Exception {
        Mac sha256HMAC = Mac.getInstance(SIGN_HMACSHA256);
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), SIGN_HMACSHA256);
        sha256HMAC.init(secretKey);
        byte[] array = sha256HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3);
        }
        return sb.toString();
    }

    /**
     * 用SHA1算法生成安全签名
     *
     * @param token     票据
     * @param timestamp 时间戳
     * @param nonce     随机字符串
     * @return 安全签名
     * @throws Exception : 异常
     */
    public static String SHA1(String token, String timestamp, String nonce) throws Exception {
        String[] array = new String[]{token, timestamp, nonce};
        StringBuilder sb = new StringBuilder();
        // 字符串排序
        Arrays.sort(array);
        for (int i = 0; i < 3; i++) {
            sb.append(array[i]);
        }
        String str = sb.toString();
        // SHA1签名生成
        MessageDigest md = MessageDigest.getInstance(SIGN_SHA1);
        md.update(str.getBytes());
        byte[] digest = md.digest();
        StringBuilder hexStr = new StringBuilder();
        String shaHex;
        for (byte b : digest) {
            shaHex = Integer.toHexString(b & 0xFF);
            if (shaHex.length() < 2) {
                hexStr.append(0);
            }
            hexStr.append(shaHex);
        }
        return hexStr.toString();
    }
}
