package com.xinelu.common.utils.aes;

import org.apache.commons.lang3.BooleanUtils;

import java.security.MessageDigest;
import java.util.Arrays;


/**
 * SHA1 class
 * <p>
 *
 * @Description 计算公众平台的消息签名接口
 * @Author WeChat
 * @Date 2024-03-21 10:19:50
 */
class SHA1 {

    /**
     * 用SHA1算法生成安全签名
     *
     * @param token     票据
     * @param timestamp 时间戳
     * @param nonce     随机字符串
     * @param encrypt   密文
     * @return 安全签名
     * @throws AesException 异常信息
     */
    public static String getShaOne(String token, String timestamp, String nonce, String encrypt) throws AesException {
        return signatureByShaOne(token, timestamp, nonce, encrypt, true);
    }

    /**
     * 用SHA1算法生成安全签名，小程序回调设置验证URL时计算签名使用
     *
     * @param token     票据
     * @param timestamp 时间戳
     * @param nonce     随机字符串
     * @return 安全签名
     * @throws AesException 异常信息
     */
    public static String getShaTwo(String token, String timestamp, String nonce) throws AesException {
        return signatureByShaOne(token, timestamp, nonce, "", false);
    }

    /**
     * 使用SHA-1计算签名公共方法
     *
     * @param token       令牌
     * @param timestamp   时间粗
     * @param nonce       随机字符串
     * @param encrypt     密文
     * @param encryptFlag 密文传入标识
     * @return String 明文
     * @throws AesException 异常信息
     */
    private static String signatureByShaOne(String token, String timestamp, String nonce, String encrypt, boolean encryptFlag) throws AesException {
        try {
            String[] array;
            int size;
            if (BooleanUtils.isTrue(encryptFlag)) {
                array = new String[]{token, timestamp, nonce, encrypt};
                size = 4;
            } else {
                array = new String[]{token, timestamp, nonce};
                size = 3;
            }
            StringBuilder sb = new StringBuilder();
            // 字符串排序
            Arrays.sort(array);
            for (int i = 0; i < size; i++) {
                sb.append(array[i]);
            }
            String str = sb.toString();
            // SHA1签名生成
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            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();
        } catch (Exception e) {
            e.printStackTrace();
            throw new AesException(AesException.COMPUTE_SIGNATURE_ERROR);
        }
    }
}
