-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathalgorithms.go
73 lines (61 loc) · 1.57 KB
/
algorithms.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package jwt
import (
"crypto/hmac"
"crypto/sha256"
"crypto/sha512"
"hash"
"golang.org/x/crypto/sha3"
)
// IAlgorithm describes a hash algorithm used to
// generate hash sums from given data.
type IAlgorithm interface {
// Name returns the name of the algorithm.
// The name must be all uppercase.
Name() string
// Sum takes any data and returns the hashed
// sum of the given data.
Sum(data []byte) ([]byte, error)
}
type Algorithm struct {
name string
hasherPool devicePool[hash.Hash]
}
func (t Algorithm) Name() string {
return t.name
}
func (t Algorithm) Sum(data []byte) ([]byte, error) {
hasher := t.hasherPool.Get()
defer t.hasherPool.Put(hasher)
_, err := hasher.Write([]byte(data))
if err != nil {
return nil, err
}
return hasher.Sum(nil), nil
}
// NewAlgorithmWithKey returns a new algorithm using the
// given hash implementation with the given name and
// a key used to sign the hash with.
func NewAlgorithmWithKey(name string, hasher func() hash.Hash, key []byte) Algorithm {
return Algorithm{
name: name,
hasherPool: newPool(
func() hash.Hash {
return hmac.New(hasher, key)
},
func(t hash.Hash) {
t.Reset()
},
),
}
}
// NewHmacSha256 returns a new algorithm using HS256.
func NewHmacSha256(key []byte) Algorithm {
return NewAlgorithmWithKey("HS256", sha256.New, key)
}
// NewHmacSha512 returns a new algorithm using HS512.
func NewHmacSha512(key []byte) Algorithm {
return NewAlgorithmWithKey("HS512", sha512.New, key)
}
func NewHmacSha384(key []byte) Algorithm {
return NewAlgorithmWithKey("HS384", sha3.New384, key)
}