main
 1package crypt
 2
 3import (
 4	"crypto/hmac"
 5	"hash"
 6
 7	"github.com/xlgmokha/x/pkg/x"
 8)
 9
10type HMACSigner struct {
11	key     []byte
12	factory x.Factory[hash.Hash]
13}
14
15func WithAlgorithm(factory x.Factory[hash.Hash]) x.Option[*HMACSigner] {
16	return x.With[*HMACSigner](func(item *HMACSigner) {
17		item.factory = factory
18	})
19}
20
21func WithKey(key []byte) x.Option[*HMACSigner] {
22	return x.With[*HMACSigner](func(item *HMACSigner) {
23		item.key = key
24	})
25}
26
27func (s *HMACSigner) Sign(data []byte) ([]byte, error) {
28	mac := hmac.New(s.factory, s.key)
29	_, err := mac.Write(data)
30	if err != nil {
31		return nil, err
32	}
33	return mac.Sum(nil), nil
34}
35
36func (s *HMACSigner) Verify(data []byte, signature []byte) bool {
37	actual, err := s.Sign(data)
38	if err != nil {
39		return false
40	}
41
42	return hmac.Equal(actual, signature)
43}