-
Notifications
You must be signed in to change notification settings - Fork 0
/
signing_rsa_pass.go
94 lines (89 loc) · 2.39 KB
/
signing_rsa_pass.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
package httpsign
import (
"crypto"
"crypto/rand"
"crypto/rsa"
)
// SigningMethodRSAPSS implements the rsa pss shaXXX family of signing methods signing methods
type SigningMethodRSAPSS struct {
*SigningMethodRSA
Options *rsa.PSSOptions
// VerifyOptions is optional. If set overrides Options for rsa.VerifyPPS.
// Used to accept tokens signed with rsa.PSSSaltLengthAuto.
VerifyOptions *rsa.PSSOptions
}
// Specific instances for RS/PS and company.
var (
SigningMethodRsaPssSha256 = &SigningMethodRSAPSS{
SigningMethodRSA: &SigningMethodRSA{
Name: "rsa-pss-sha256",
Hash: crypto.SHA256,
},
Options: &rsa.PSSOptions{
SaltLength: rsa.PSSSaltLengthEqualsHash,
},
VerifyOptions: &rsa.PSSOptions{
SaltLength: rsa.PSSSaltLengthAuto,
},
}
SigningMethodRsaPssSha384 = &SigningMethodRSAPSS{
SigningMethodRSA: &SigningMethodRSA{
Name: "rsa-pss-sha384",
Hash: crypto.SHA384,
},
Options: &rsa.PSSOptions{
SaltLength: rsa.PSSSaltLengthEqualsHash,
},
VerifyOptions: &rsa.PSSOptions{
SaltLength: rsa.PSSSaltLengthAuto,
},
}
SigningMethodRsaPssSha512 = &SigningMethodRSAPSS{
SigningMethodRSA: &SigningMethodRSA{
Name: "rsa-pss-sha512",
Hash: crypto.SHA512,
},
Options: &rsa.PSSOptions{
SaltLength: rsa.PSSSaltLengthEqualsHash,
},
VerifyOptions: &rsa.PSSOptions{
SaltLength: rsa.PSSSaltLengthAuto,
},
}
)
// Verify implements token verification for the SigningMethod.
// For this verify method, key must be an rsa.PublicKey struct
func (m *SigningMethodRSAPSS) Verify(signingBytes, sig []byte, key any) error {
rsaKey, ok := key.(*rsa.PublicKey)
if !ok {
return ErrKeyTypeInvalid
}
if !m.Hash.Available() {
return ErrHashUnavailable
}
opts := m.Options
if m.VerifyOptions != nil {
opts = m.VerifyOptions
}
hasher := m.Hash.New()
hasher.Write(signingBytes)
err := rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, opts)
if err != nil {
return ErrSignatureInvalid
}
return nil
}
// Sign implements token signing for the SigningMethod.
// For this signing method, key must be an rsa.PrivateKey struct
func (m *SigningMethodRSAPSS) Sign(signingBytes []byte, key any) ([]byte, error) {
rsaKey, ok := key.(*rsa.PrivateKey)
if !ok {
return nil, ErrKeyTypeInvalid
}
if !m.Hash.Available() {
return nil, ErrHashUnavailable
}
hasher := m.Hash.New()
hasher.Write(signingBytes)
return rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options)
}