package com.kingdee.eas.utils;

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

/**
 * @Description ¼ÓÃÜ¹¤¾ßÀà
 * @Date 2024/11/8 11:54
 * @Created by Heyuan
 */
public class EncryptUtils {
    private static final char[] DIGITS_LOWER = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private static final char[] DIGITS_UPPER = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    public static String sha256(String data, boolean toUpCase) {
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(data.getBytes(StandardCharsets.UTF_8));
            return encodeHexStr(messageDigest.digest(), toUpCase);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("sha256 sign error");
        }
    }

    public static String hmacSha256(String data, String key) {
        try {
            Mac hmacSha256 = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            hmacSha256.init(secretKeySpec);
            byte[] hash = hmacSha256.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return encodeHexStr(hash, true);
        } catch (Exception e) {
            throw new RuntimeException("HmacSha256 sign error");
        }
    }

    public static String encodeHexStr(byte[] data, boolean toUpCase) {
        return encodeHexStr(data, toUpCase ? DIGITS_UPPER : DIGITS_LOWER);
    }

    private static String encodeHexStr(byte[] data, char[] toDigits) {
        int len = data.length;
        char[] out = new char[len << 1];
        int i = 0;

        for (int var5 = 0; i < len; ++i) {
            out[var5++] = toDigits[(240 & data[i]) >>> 4];
            out[var5++] = toDigits[15 & data[i]];
        }
        return new String(out);
    }
}
