package main

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/gob"
	"encoding/hex"
	"fmt"
	"sort"
)

func main() {
	data := make(map[string]string)
	data["REQ_ACCESS_POP_TOKEN"] = "4fb818df-af9e-4590-868f-52a6647cb91b9a6a7474-5891-4468-84fb-ccd0beef91a5"
	data["REQ_ACCESS_POP_TIMESTRAP"] = "cdd08ede-b836-44d2-8c10-b6abc0ac57aa"
	data["REQ_ACCESS_POP_NONCESTR"] = "abcabcabcabcabc1"

	fmt.Println("Data Map:", data)

	serializedData, err := getSerializedBytes3(data)
	if err != nil {
		fmt.Println("Serialization Error:", err)
		return
	}

	fmt.Printf("Serialized Data: %x\n", serializedData)

	key := "cdd08ede-b836-44d2-8c10-b6abc0ac57aa"
	signature := genHMAC3(serializedData, key)
	fmt.Println("Signature:", signature)
}

func genHMAC3(data []byte, key string) string {
	h := hmac.New(sha256.New, []byte(key))
	h.Write(data)
	signature := h.Sum(nil)
	fmt.Printf("HMAC SHA256: %x\n", signature)
	return hex.EncodeToString(signature)
}

func getSerializedBytes3(data map[string]string) ([]byte, error) {
	var buf bytes.Buffer
	keys := make([]string, 0, len(data))
	for k := range data {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	enc := gob.NewEncoder(&buf)
	for _, k := range keys {
		err := enc.Encode(k)
		if err != nil {
			return nil, err
		}
		err = enc.Encode(data[k])
		if err != nil {
			return nil, err
		}
	}
	return buf.Bytes(), nil
}
