-
Notifications
You must be signed in to change notification settings - Fork 19
/
rsapss.go
77 lines (63 loc) · 1.53 KB
/
rsapss.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
package jwt
import (
"crypto/rand"
"crypto/rsa"
"fmt"
)
type algRSAPSS struct {
name string
opts *rsa.PSSOptions
}
func (a *algRSAPSS) Parse(private, public []byte) (privateKey PrivateKey, publicKey PublicKey, err error) {
if len(private) > 0 {
privateKey, err = ParsePrivateKeyRSA(private)
if err != nil {
return nil, nil, fmt.Errorf("RSA-PSS: private key: %v", err)
}
}
if len(public) > 0 {
publicKey, err = ParsePublicKeyRSA(public)
if err != nil {
return nil, nil, fmt.Errorf("RSA-PSS: public key: %v", err)
}
}
return
}
func (a *algRSAPSS) Name() string {
return a.name
}
func (a *algRSAPSS) Sign(key PrivateKey, headerAndPayload []byte) ([]byte, error) {
privateKey, ok := key.(*rsa.PrivateKey)
if !ok {
return nil, ErrInvalidKey
}
h := a.opts.Hash.New()
// header.payload
_, err := h.Write(headerAndPayload)
if err != nil {
return nil, err
}
hashed := h.Sum(nil)
return rsa.SignPSS(rand.Reader, privateKey, a.opts.Hash, hashed, a.opts)
}
func (a *algRSAPSS) Verify(key PublicKey, headerAndPayload []byte, signature []byte) error {
publicKey, ok := key.(*rsa.PublicKey)
if !ok {
if privateKey, ok := key.(*rsa.PrivateKey); ok {
publicKey = &privateKey.PublicKey
} else {
return ErrInvalidKey
}
}
h := a.opts.Hash.New()
// header.payload
_, err := h.Write(headerAndPayload)
if err != nil {
return err
}
hashed := h.Sum(nil)
if err = rsa.VerifyPSS(publicKey, a.opts.Hash, hashed, signature, a.opts); err != nil {
return fmt.Errorf("%w: %v", ErrTokenSignature, err)
}
return nil
}