Skip to content

Commit

Permalink
Add pool of hashes for HMAC (#44)
Browse files Browse the repository at this point in the history
  • Loading branch information
storozhukBM authored May 9, 2020
1 parent 1d58f52 commit 1b483c8
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions algo_hs.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package jwt
import (
"crypto"
"crypto/hmac"
"hash"
"sync"
)

// NewSignerHS returns a new HMAC-based signer.
Expand All @@ -18,6 +20,9 @@ func NewSignerHS(alg Algorithm, key []byte) (Signer, error) {
alg: alg,
hash: hash,
key: key,
hashPool: &sync.Pool{New: func() interface{} {
return hmac.New(hash.New, key)
}},
}, nil
}

Expand All @@ -34,6 +39,9 @@ func NewVerifierHS(alg Algorithm, key []byte) (Verifier, error) {
alg: alg,
hash: hash,
key: key,
hashPool: &sync.Pool{New: func() interface{} {
return hmac.New(hash.New, key)
}},
}, nil
}

Expand All @@ -51,9 +59,10 @@ func getHashHMAC(alg Algorithm) (crypto.Hash, error) {
}

type hsAlg struct {
alg Algorithm
hash crypto.Hash
key []byte
alg Algorithm
hash crypto.Hash
key []byte
hashPool *sync.Pool
}

func (h hsAlg) Algorithm() Algorithm {
Expand All @@ -76,7 +85,11 @@ func (h hsAlg) Verify(payload, signature []byte) error {
}

func (h hsAlg) sign(payload []byte) ([]byte, error) {
hasher := hmac.New(h.hash.New, h.key)
hasher := h.hashPool.Get().(hash.Hash)
defer func() {
hasher.Reset()
h.hashPool.Put(hasher)
}()

_, err := hasher.Write(payload)
if err != nil {
Expand Down

0 comments on commit 1b483c8

Please sign in to comment.