-
Notifications
You must be signed in to change notification settings - Fork 46
/
algo_rs.go
108 lines (96 loc) · 2.03 KB
/
algo_rs.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
package jwt
import (
"crypto"
"crypto/rand"
"crypto/rsa"
)
// NewSignerRS returns a new RSA-based signer.
func NewSignerRS(alg Algorithm, key *rsa.PrivateKey) (*RSAlg, error) {
if key == nil {
return nil, ErrNilKey
}
hash, err := getHashRS(alg)
if err != nil {
return nil, err
}
return &RSAlg{
alg: alg,
hash: hash,
privateKey: key,
publicKey: nil,
}, nil
}
// NewVerifierRS returns a new RSA-based verifier.
func NewVerifierRS(alg Algorithm, key *rsa.PublicKey) (*RSAlg, error) {
if key == nil {
return nil, ErrNilKey
}
hash, err := getHashRS(alg)
if err != nil {
return nil, err
}
return &RSAlg{
alg: alg,
hash: hash,
privateKey: nil,
publicKey: key,
}, nil
}
func getHashRS(alg Algorithm) (crypto.Hash, error) {
var hash crypto.Hash
switch alg {
case RS256:
hash = crypto.SHA256
case RS384:
hash = crypto.SHA384
case RS512:
hash = crypto.SHA512
default:
return 0, ErrUnsupportedAlg
}
return hash, nil
}
type RSAlg struct {
alg Algorithm
hash crypto.Hash
publicKey *rsa.PublicKey
privateKey *rsa.PrivateKey
}
func (rs *RSAlg) Algorithm() Algorithm {
return rs.alg
}
func (rs *RSAlg) SignSize() int {
return rs.privateKey.Size()
}
func (rs *RSAlg) Sign(payload []byte) ([]byte, error) {
digest, err := hashPayload(rs.hash, payload)
if err != nil {
return nil, err
}
signature, err := rsa.SignPKCS1v15(rand.Reader, rs.privateKey, rs.hash, digest)
if err != nil {
return nil, err
}
return signature, nil
}
func (rs *RSAlg) Verify(token *Token) error {
switch {
case !token.isValid():
return ErrUninitializedToken
case !constTimeAlgEqual(token.Header().Algorithm, rs.alg):
return ErrAlgorithmMismatch
default:
return rs.verify(token.PayloadPart(), token.Signature())
}
}
func (rs *RSAlg) verify(payload, signature []byte) error {
digest, err := hashPayload(rs.hash, payload)
if err != nil {
return err
}
err = rsa.VerifyPKCS1v15(rs.publicKey, rs.hash, digest, signature)
if err != nil {
return ErrInvalidSignature
}
return nil
}