-
Notifications
You must be signed in to change notification settings - Fork 46
/
algo_ps.go
124 lines (109 loc) · 2.42 KB
/
algo_ps.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package jwt
import (
"crypto"
"crypto/rand"
"crypto/rsa"
)
// NewSignerPS returns a new RSA-PSS-based signer.
func NewSignerPS(alg Algorithm, key *rsa.PrivateKey) (*PSAlg, error) {
if key == nil {
return nil, ErrNilKey
}
hash, opts, err := getParamsPS(alg)
if err != nil {
return nil, err
}
return &PSAlg{
alg: alg,
hash: hash,
privateKey: key,
opts: opts,
}, nil
}
// NewVerifierPS returns a new RSA-PSS-based signer.
func NewVerifierPS(alg Algorithm, key *rsa.PublicKey) (*PSAlg, error) {
if key == nil {
return nil, ErrNilKey
}
hash, opts, err := getParamsPS(alg)
if err != nil {
return nil, err
}
return &PSAlg{
alg: alg,
hash: hash,
publicKey: key,
opts: opts,
}, nil
}
func getParamsPS(alg Algorithm) (crypto.Hash, *rsa.PSSOptions, error) {
switch alg {
case PS256:
return crypto.SHA256, optsPS256, nil
case PS384:
return crypto.SHA384, optsPS384, nil
case PS512:
return crypto.SHA512, optsPS512, nil
default:
return 0, nil, ErrUnsupportedAlg
}
}
var (
optsPS256 = &rsa.PSSOptions{
SaltLength: rsa.PSSSaltLengthAuto,
Hash: crypto.SHA256,
}
optsPS384 = &rsa.PSSOptions{
SaltLength: rsa.PSSSaltLengthAuto,
Hash: crypto.SHA384,
}
optsPS512 = &rsa.PSSOptions{
SaltLength: rsa.PSSSaltLengthAuto,
Hash: crypto.SHA512,
}
)
type PSAlg struct {
alg Algorithm
hash crypto.Hash
publicKey *rsa.PublicKey
privateKey *rsa.PrivateKey
opts *rsa.PSSOptions
}
func (ps *PSAlg) SignSize() int {
return ps.privateKey.Size()
}
func (ps *PSAlg) Algorithm() Algorithm {
return ps.alg
}
func (ps *PSAlg) Sign(payload []byte) ([]byte, error) {
digest, err := hashPayload(ps.hash, payload)
if err != nil {
return nil, err
}
signature, err := rsa.SignPSS(rand.Reader, ps.privateKey, ps.hash, digest, ps.opts)
if err != nil {
return nil, err
}
return signature, nil
}
func (ps *PSAlg) Verify(token *Token) error {
switch {
case !token.isValid():
return ErrUninitializedToken
case !constTimeAlgEqual(token.Header().Algorithm, ps.alg):
return ErrAlgorithmMismatch
default:
return ps.verify(token.PayloadPart(), token.Signature())
}
}
func (ps *PSAlg) verify(payload, signature []byte) error {
digest, err := hashPayload(ps.hash, payload)
if err != nil {
return err
}
err = rsa.VerifyPSS(ps.publicKey, ps.hash, digest, signature, ps.opts)
if err != nil {
return ErrInvalidSignature
}
return nil
}