-
Notifications
You must be signed in to change notification settings - Fork 1
/
pem.go
63 lines (49 loc) · 1.11 KB
/
pem.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
package jwit
import (
"crypto/x509"
"encoding/pem"
"github.com/go-jose/go-jose/v3"
)
// pemToJWKS converts raw PEM-encoded data to a JWKS.
func pemToJWKS(pemBytes []byte) (jose.JSONWebKeySet, error) {
var jwks jose.JSONWebKeySet
var block *pem.Block
for {
block, pemBytes = pem.Decode(pemBytes)
if block == nil {
break
}
key, err := pemBlockToKey(block)
if err != nil {
return jwks, err
}
jwks.Keys = append(jwks.Keys, jose.JSONWebKey{Key: key})
}
return jwks, nil
}
// pemBlockToKey converts a PEM block to a key object.
func pemBlockToKey(block *pem.Block) (interface{}, error) {
var key interface{}
var err error
key, err = x509.ParsePKCS8PrivateKey(block.Bytes)
if err == nil {
return key, nil
}
key, err = x509.ParsePKCS1PrivateKey(block.Bytes)
if err == nil {
return key, nil
}
key, err = x509.ParseECPrivateKey(block.Bytes)
if err == nil {
return key, nil
}
key, err = x509.ParsePKCS1PublicKey(block.Bytes)
if err == nil {
return key, nil
}
key, err = x509.ParsePKIXPublicKey(block.Bytes)
if err == nil {
return key, nil
}
return nil, ErrUnknownKeyType
}