Debian Codegraph @

vendor/github.com/dgrijalva/jwt-go/rsa.go

raw
1 package jwt
2
3 import (
4 "crypto"
5 "crypto/rand"
6 "crypto/rsa"
7 )
8
9 // Implements the RSA family of signing methods signing methods
10 type SigningMethodRSA struct {
11 Name string
12 Hash crypto.Hash
13 }
14
15 // Specific instances for RS256 and company
16 var (
17 SigningMethodRS256 *SigningMethodRSA
18 SigningMethodRS384 *SigningMethodRSA
19 SigningMethodRS512 *SigningMethodRSA
20 )
21
22 func init() {
23 // RS256
24 SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256}
25 RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod {
26 return SigningMethodRS256
27 })
28
29 // RS384
30 SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384}
31 RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod {
32 return SigningMethodRS384
33 })
34
35 // RS512
36 SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512}
37 RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod {
38 return SigningMethodRS512
39 })
40 }
41
42 func (m *SigningMethodRSA) Alg() string {
43 return m.Name
44 }
45
46 // Implements the Verify method from SigningMethod
47 // For this signing method, must be an rsa.PublicKey structure.
48 func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error {
49 var err error
50
51 // Decode the signature
52 var sig []byte
53 if sig, err = DecodeSegment(signature); err != nil {
54 return err
55 }
56
57 var rsaKey *rsa.PublicKey
58 var ok bool
59
60 if rsaKey, ok = key.(*rsa.PublicKey); !ok {
61 return ErrInvalidKeyType
62 }
63
64 // Create hasher
65 if !m.Hash.Available() {
66 return ErrHashUnavailable
67 }
68 hasher := m.Hash.New()
69 hasher.Write([]byte(signingString))
70
71 // Verify the signature
72 return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig)
73 }
74
75 // Implements the Sign method from SigningMethod
76 // For this signing method, must be an rsa.PrivateKey structure.
77 func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) {
78 var rsaKey *rsa.PrivateKey
79 var ok bool
80
81 // Validate type of key
82 if rsaKey, ok = key.(*rsa.PrivateKey); !ok {
83 return "", ErrInvalidKey
84 }
85
86 // Create the hasher
87 if !m.Hash.Available() {
88 return "", ErrHashUnavailable
89 }
90
91 hasher := m.Hash.New()
92 hasher.Write([]byte(signingString))
93
94 // Sign the string and return the encoded bytes
95 if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil {
96 return EncodeSegment(sigBytes), nil
97 } else {
98 return "", err
99 }
100 }