Commit a3d5689
pkg/crypt/hmac.go
@@ -0,0 +1,42 @@
+package crypt
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "hash"
+
+ "github.com/xlgmokha/x/pkg/x"
+)
+
+type HMACSigner struct {
+ key []byte
+ 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)
+ if err != nil {
+ return nil, err
+ }
+ return mac.Sum(nil), nil
+}
+
+func WithAlgorithm(factory x.Factory[hash.Hash]) x.Option[*HMACSigner] {
+ return x.With[*HMACSigner](x.Configure[*HMACSigner](func(item *HMACSigner) {
+ item.factory = factory
+ }))
+}
+
+func WithKey(key []byte) x.Option[*HMACSigner] {
+ return x.With[*HMACSigner](x.Configure[*HMACSigner](func(item *HMACSigner) {
+ item.key = key
+ }))
+}
pkg/crypt/signer.go
@@ -0,0 +1,5 @@
+package crypt
+
+type Signer interface {
+ Sign([]byte) ([]byte, error)
+}
pkg/x/option.go
@@ -0,0 +1,20 @@
+package x
+
+type Configure[T any] func(T)
+type Option[T any] func(T) T
+type Factory[T any] func() T
+
+func New[T any](options ...Option[T]) T {
+ item := Default[T]()
+ for _, option := range options {
+ item = option(item)
+ }
+ return item
+}
+
+func With[T any](with Configure[T]) Option[T] {
+ return func(item T) T {
+ with(item)
+ return item
+ }
+}
pkg/x/types.go
@@ -2,8 +2,6 @@ package x
import "reflect"
-type Option[T any] func(T) T
-
func Default[T any]() T {
item := Zero[T]()
@@ -14,14 +12,6 @@ func Default[T any]() T {
return item
}
-func New[T any](options ...Option[T]) T {
- item := Default[T]()
- for _, option := range options {
- item = option(item)
- }
- return item
-}
-
func Zero[T any]() T {
var item T
return item