package com.ylx.massage.utils;

/**
 * @author jianlong
 * @date 2024-06-04 09:13
 */
import java.security.MessageDigest;
import java.util.Locale;
import java.util.Random;

/**
 * 其他工具类
 *
 */
public class OtherUtil {

    private final static byte[] HEX = "0123456789ABCDEF".getBytes();
    private final static String STRING = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private final static String MESSAGE_DIGEST_INSTANCE = "SHA-1";
    private final static String ENCODING = "UTF-8";


    /**
     * 从字节数组到十六进制字符串转换
     */
    public static String bytes2HexString(byte[] b) {
        byte[] buff = new byte[2 * b.length];
        for (int i = 0; i < b.length; i++) {
            buff[2 * i] = HEX[(b[i] >> 4) & 0x0f];
            buff[2 * i + 1] = HEX[b[i] & 0x0f];
        }
        return new String(buff);
    }

    /**
     * 校验参数是否合法
     */
    public static boolean verification(String[] params, String signature) throws Exception {
        // 拼接
        String paramstr = params[0] + params[1] + params[2];
        // 获取 shal 算法封装类
        MessageDigest messageDigest = MessageDigest.getInstance(MESSAGE_DIGEST_INSTANCE);
        // 进行加密
        byte[] digestResult = messageDigest.digest(paramstr.getBytes(ENCODING));
        // 拿到加密结果
        String mysignature = OtherUtil.bytes2HexString(digestResult);
        mysignature = mysignature.toLowerCase(Locale.ROOT);
        // 是否正确
        return mysignature.equals(signature);
    }


    /**
     * 用户要求产生字符串的长度
     */
    public static String getRandomString(int length){
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < length; i++){
            int number = random.nextInt(62);
            sb.append(STRING.charAt(number));
        }
        return sb.toString();
    }
}
