package com.weaver.seconddev.chapanda.test;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.regex.Matcher;

public class HmacSHA256Example {
    public static void main(String[] args) {
        try {
            // 密钥（在CryptoJS中通常称为secret key）
            String secretKey = "7f067a08f5c675137e6e72aa298e2c07"; // 替换为你的密钥
            // 要签名的数据
            String data = "{\"templateId\": \"JMHT-ZXSJ\"}"; // 替换为你要签名的数据
            data = data
                    .replaceAll("\\\\.", Matcher.quoteReplacement("$0"));
            System.out.println(data);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("templateId","JMHT-ZXSJ");

            // 初始化Mac对象
            Mac sha256Hmac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            sha256Hmac.init(secretKeySpec);

            // 执行HmacSHA256操作
            byte[] result = sha256Hmac.doFinal(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8));

            String data99 = bytesToHex(result);
            System.out.println("HMAC-data99: " + data99);
            // 将结果转换为Base64编码的字符串（与CryptoJS输出的格式一致）
            String hmacResult = Base64.getEncoder().encodeToString(result);

            String data2 = Hex.encodeHexString(result);

            String hash = Base64.getEncoder().encodeToString(result);

            String hash2 =  Base64.getUrlEncoder().withoutPadding().encodeToString(result);

            StringBuilder hexSignature = new StringBuilder();
            for (byte b : result) {
                String hex = Integer.toHexString(b & 0xFF);
                if (hex.length() == 1) {
                    hexSignature.append("0");
                }
                hexSignature.append(hex);
            }
            System.out.println("HMAC-SHA256签名: " + hexSignature.toString());


            System.out.println("HMAC SHA256 Result: " + hmacResult);
            System.out.println("HMAC SHA256 Result2: " + data2);
            System.out.println("HMAC SHA256 hash: " + hash);
            System.out.println("HMAC SHA256 hash2: " + hash2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }

}