Commit 0d8dc41

mo khan <mo@mokhan.ca>
2025-05-06 20:40:25
feat: add hmac signer tests
1 parent cae093a
Changed files (4)
pkg/cookie/option_test.go
@@ -11,6 +11,7 @@ import (
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
 	"github.com/xlgmokha/x/pkg/crypt"
+	"github.com/xlgmokha/x/pkg/x"
 )
 
 func TestOption(t *testing.T) {
@@ -59,7 +60,10 @@ func TestOption(t *testing.T) {
 	t.Run("WithSignedValue", func(t *testing.T) {
 		value := "1"
 		secret := "secret"
-		signer := crypt.NewHMACSigner([]byte(secret))
+		signer := x.New[*crypt.HMACSigner](
+			crypt.WithKey([]byte(secret)),
+			crypt.WithAlgorithm(sha256.New),
+		)
 		cookie := New("session", WithSignedValue(value, signer))
 
 		require.NotNil(t, cookie)
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
+}