package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"log"
	"sort"
)

const (
	reqAccessPopToken     = "access-pop-token"
	reqAccessPopTimestamp = "access-pop-timestrap"
	reqAccessPopNonceStr  = "access-pop-noncestr"
	//hmacSHA256Algorithm   = "HmacSHA256"
)

func main() {
	// 使用 Go map 和一个额外的 keys 列表保持顺序
	treeMap := make(map[string]string)
	keys := []string{
		reqAccessPopToken,
		reqAccessPopTimestamp,
		reqAccessPopNonceStr,
	}
	treeMap[reqAccessPopToken] = "4fb818df-af9e-4590-868f-52a6647cb91b9a6a7474-5891-4468-84fb-ccd0beef91a5"
	treeMap[reqAccessPopTimestamp] = "cdd08ede-b836-44d2-8c10-b6abc0ac57aa"
	treeMap[reqAccessPopNonceStr] = "abcabcabcabcabc1"
	sysSignature, err := genHMAC1(treeMap, keys, "cdd08ede-b836-44d2-8c10-b6abc0ac57aa")
	if err != nil {
		log.Printf("Error generating HMAC: %v", err)
	}
	fmt.Println(sysSignature)
}

func genHMAC1(data map[string]string, keys []string, key string) (string, error) {
	// 对 keys 进行排序以确保顺序
	sort.Strings(keys)

	// 构建 JSON 字符串
	dataMapOrdered := make(map[string]string)
	for _, k := range keys {
		dataMapOrdered[k] = data[k]
	}
	jsonData, err := json.Marshal(dataMapOrdered)
	if err != nil {
		return "", err
	}

	// 创建 hmac
	h := hmac.New(sha256.New, []byte(key))
	if _, err := h.Write([]byte(jsonData)); err != nil {
		return "", err
	}
	signature := hex.EncodeToString(h.Sum(nil))
	return signature, nil
}
