Commit 0d8dc41
Changed files (4)
pkg
pkg/crypt/hmac.go
@@ -2,7 +2,6 @@ package crypt
import (
"crypto/hmac"
- "crypto/sha256"
"hash"
"github.com/xlgmokha/x/pkg/x"
@@ -13,13 +12,6 @@ type HMACSigner struct {
factory func() hash.Hash
}
-func NewHMACSigner(key []byte) *HMACSigner {
- return x.New[*HMACSigner](
- WithAlgorithm(sha256.New),
- WithKey(key),
- )
-}
-
func (s *HMACSigner) Sign(data []byte) ([]byte, error) {
mac := hmac.New(s.factory, s.key)
_, err := mac.Write(data)
pkg/crypt/hmac_test.go
@@ -0,0 +1,47 @@
+package crypt
+
+import (
+ "crypto/hmac"
+ "crypto/md5"
+ "crypto/sha1"
+ "crypto/sha256"
+ "crypto/sha512"
+ "fmt"
+ "hash"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/xlgmokha/x/pkg/pls"
+ "github.com/xlgmokha/x/pkg/x"
+)
+
+func TestHMAC(t *testing.T) {
+ key := x.Must(pls.GenerateRandomBytes(32))
+
+ t.Run("Sign", func(t *testing.T) {
+ data := x.Must(pls.GenerateRandomBytes(64))
+
+ tt := []struct {
+ h x.Factory[hash.Hash]
+ }{
+ {h: md5.New},
+ {h: sha1.New},
+ {h: sha256.New},
+ {h: sha512.New},
+ }
+
+ for _, test := range tt {
+ t.Run(fmt.Sprintf("generates an HMAC %v signature", test.h), func(t *testing.T) {
+ signer := x.New[*HMACSigner](WithKey(key), WithAlgorithm(test.h))
+ mac := hmac.New(test.h, key)
+ mac.Write(data)
+ expected := mac.Sum(nil)
+
+ result := x.Must(signer.Sign(data))
+
+ assert.NotEmpty(t, result)
+ assert.Equal(t, expected, result)
+ })
+ }
+ })
+}
pkg/pls/rand.go
@@ -0,0 +1,12 @@
+package pls
+
+import "crypto/rand"
+
+func GenerateRandomBytes(n int) ([]byte, error) {
+ b := make([]byte, n)
+ _, err := rand.Read(b)
+ if err != nil {
+ return nil, err
+ }
+ return b, nil
+}