-
Notifications
You must be signed in to change notification settings - Fork 9
/
pem.go
77 lines (68 loc) · 2.24 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package tpmk
import (
"crypto"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
)
// LoadKeyPair reads and parses a key and certificate file in PEM format.
func LoadKeyPair(crtFilePEM, keyFilePEM string) (*x509.Certificate, crypto.PrivateKey, error) {
crt, err := LoadX509CertificateFile(crtFilePEM)
if err != nil {
return nil, nil, err
}
key, err := LoadRSAKeyFile(keyFilePEM)
return crt, key, err
}
// LoadX509CertificateFile reads a certificate in PEM format from a file.
func LoadX509CertificateFile(crtFilePEM string) (*x509.Certificate, error) {
crtRaw, err := ioutil.ReadFile(crtFilePEM)
if err != nil {
return nil, err
}
crtBlk, _ := pem.Decode(crtRaw)
if crtBlk == nil || crtBlk.Type != "CERTIFICATE" {
return nil, errors.New("failed to decode PEM block containing public key")
}
return x509.ParseCertificate(crtBlk.Bytes)
}
// LoadRSAKeyFile reads a private RSA key in PEM format from a file.
func LoadRSAKeyFile(keyFilePEM string) (crypto.PrivateKey, error) {
keyRaw, err := ioutil.ReadFile(keyFilePEM)
if err != nil {
return nil, err
}
return PEMToPrivKey(keyRaw)
}
// PubKeyToPEM encodes a public key in PEM format.
func PubKeyToPEM(pub crypto.PublicKey) ([]byte, error) {
p, ok := pub.(*rsa.PublicKey)
if !ok {
return nil, fmt.Errorf("unsupported public key type %T", pub)
}
der := x509.MarshalPKCS1PublicKey(p)
return pem.EncodeToMemory(&pem.Block{Type: "RSA PUBLIC KEY", Bytes: der}), nil
}
// PEMToPubKey decodes a public key in PCKS1 PEM format.
func PEMToPubKey(b []byte) (crypto.PublicKey, error) {
blk, _ := pem.Decode(b)
if blk == nil || blk.Type != "RSA PUBLIC KEY" {
return nil, errors.New("failed to decode PEM block containing public key")
}
return x509.ParsePKCS1PublicKey(blk.Bytes)
}
// PEMToPrivKey decodes a Private key in PCKS1 PEM format.
func PEMToPrivKey(b []byte) (crypto.PrivateKey, error) {
keyBlk, _ := pem.Decode(b)
if keyBlk == nil || keyBlk.Type != "RSA PRIVATE KEY" {
return nil, errors.New("failed to decode PEM block containing private key")
}
return x509.ParsePKCS1PrivateKey(keyBlk.Bytes)
}
// CertToPEM encodes an x509 certificate from DER format to PEM
func CertToPEM(der []byte) []byte {
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
}