/
hmac.go
59 lines (51 loc) · 1.3 KB
/
hmac.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
package jws
import (
"crypto/hmac"
"crypto/sha256"
"crypto/sha512"
"hash"
)
const (
ALG_HS256 SignatureAlgorithm = "HS256"
ALG_HS384 SignatureAlgorithm = "HS384"
ALG_HS512 SignatureAlgorithm = "HS512"
)
// HMACSignerVerifier implements a signature method using a HMAC
// with a pre-shared secret.
type HMACSignerVerifier struct {
h func() hash.Hash
secret []byte
alg SignatureAlgorithm
}
func (h *HMACSignerVerifier) Alg() SignatureAlgorithm {
return h.alg
}
func (h *HMACSignerVerifier) Sign(data []byte) ([]byte, error) {
mac := hmac.New(h.h, h.secret)
mac.Write(data)
return mac.Sum(nil), nil
}
// HS256 creates a signature method implementing the HMAC SHA256 algorithm.
func HS256(secret []byte) SignerVerifier {
return SymmetricSignature(&HMACSignerVerifier{
h: sha256.New,
secret: secret,
alg: ALG_HS256,
})
}
// HS384 creates a signature method implementing the HMAC SHA384 algorithm.
func HS384(secret []byte) SignerVerifier {
return SymmetricSignature(&HMACSignerVerifier{
h: sha512.New384,
secret: secret,
alg: ALG_HS384,
})
}
// HS512 creates a signature method implementing the HMAC SHA512 algorithm.
func HS512(secret []byte) SignerVerifier {
return SymmetricSignature(&HMACSignerVerifier{
h: sha512.New,
secret: secret,
alg: ALG_HS512,
})
}