forked from 0xProject/0x-mesh
/
keys.go
44 lines (40 loc) · 980 Bytes
/
keys.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
package keys
import (
"crypto/rand"
"path/filepath"
p2pcrypto "github.com/libp2p/go-libp2p-core/crypto"
)
func GetPrivateKeyFromPath(path string) (p2pcrypto.PrivKey, error) {
keyBytes, err := readFile(path)
if err != nil {
return nil, err
}
decodedKey, err := p2pcrypto.ConfigDecodeKey(string(keyBytes))
if err != nil {
return nil, err
}
priv, err := p2pcrypto.UnmarshalPrivateKey(decodedKey)
if err != nil {
return nil, err
}
return priv, nil
}
func GenerateAndSavePrivateKey(path string) (p2pcrypto.PrivKey, error) {
dir := filepath.Dir(path)
if err := mkdirAll(dir); err != nil {
return nil, err
}
privKey, _, err := p2pcrypto.GenerateSecp256k1Key(rand.Reader)
if err != nil {
return nil, err
}
keyBytes, err := p2pcrypto.MarshalPrivateKey(privKey)
if err != nil {
return nil, err
}
encodedKey := p2pcrypto.ConfigEncodeKey(keyBytes)
if err := writeFile(path, []byte(encodedKey)); err != nil {
return nil, err
}
return privKey, nil
}