-
-
Notifications
You must be signed in to change notification settings - Fork 594
/
jwt.go
69 lines (57 loc) · 1.56 KB
/
jwt.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
package jwtutils
import (
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
)
var (
errKeyMustBePEMEncoded = errors.New("key must be PEM encoded")
errNotRSAPublicKey = errors.New("key is not a valid RSA public key")
errNotECDSAPublicKey = errors.New("key is not a valid ECDSA public key")
)
// ParseRSAPublicKeyFromPEM parses PEM encoded PKCS1 or PKCS8 public key.
func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
var err error
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, errKeyMustBePEMEncoded
}
var parsedKey any
if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
parsedKey = cert.PublicKey
} else {
return nil, err
}
}
var pkey *rsa.PublicKey
var ok bool
if pkey, ok = parsedKey.(*rsa.PublicKey); !ok {
return nil, errNotRSAPublicKey
}
return pkey, nil
}
// ParseECDSAPublicKeyFromPEM parses PEM encoded public key.
func ParseECDSAPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) {
var err error
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, errKeyMustBePEMEncoded
}
var parsedKey any
if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
parsedKey = cert.PublicKey
} else {
return nil, err
}
}
var pkey *ecdsa.PublicKey
var ok bool
if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok {
return nil, errNotECDSAPublicKey
}
return pkey, nil
}