-
Notifications
You must be signed in to change notification settings - Fork 8
/
keypem.go
70 lines (56 loc) · 1.53 KB
/
keypem.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
package keypem
import (
"encoding/pem"
"errors"
"github.com/libp2p/go-libp2p-core/crypto"
)
// PrivPemType is the expected header type on private keys.
const PrivPemType = "LIBP2P PRIVATE KEY"
// PubPemType is the expected header type on public keys.
const PubPemType = "LIBP2P PUBLIC KEY"
// ParsePrivKeyPem parses a private key in pem format.
// If none is found returns nil
func ParsePrivKeyPem(pemDat []byte) (crypto.PrivKey, error) {
b, _ := pem.Decode(pemDat)
if b == nil {
return nil, nil
}
if b.Type != PrivPemType {
return nil, errors.New("unexpected pem type for private key")
}
return crypto.UnmarshalPrivateKey(b.Bytes)
}
// MarshalPrivKeyPem marshals a private key to pem.
func MarshalPrivKeyPem(key crypto.PrivKey) ([]byte, error) {
dat, err := crypto.MarshalPrivateKey(key)
if err != nil {
return nil, err
}
return pem.EncodeToMemory(&pem.Block{
Type: PrivPemType,
Bytes: dat,
}), nil
}
// ParsePubKeyPem parses a public key in pem format.
// If none is found returns nil
func ParsePubKeyPem(pemDat []byte) (crypto.PubKey, error) {
b, _ := pem.Decode(pemDat)
if b == nil {
return nil, nil
}
if b.Type != PubPemType {
return nil, errors.New("unexpected pem type for public key")
}
return crypto.UnmarshalPublicKey(b.Bytes)
}
// MarshalPubKeyPem marshals a public key to pem.
func MarshalPubKeyPem(key crypto.PubKey) ([]byte, error) {
dat, err := crypto.MarshalPublicKey(key)
if err != nil {
return nil, err
}
return pem.EncodeToMemory(&pem.Block{
Type: PubPemType,
Bytes: dat,
}), nil
}