-
Notifications
You must be signed in to change notification settings - Fork 32
/
identity.go
50 lines (40 loc) · 1.15 KB
/
identity.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
package main
// Borrowed from https://github.com/libp2p/go-libp2p-relay-daemon/blob/master/identity.go
import (
"fmt"
"os"
"github.com/libp2p/go-libp2p/core/crypto"
)
// LoadIdentity reads a private key from the given path and, if it does not
// exist, generates a new one.
func LoadIdentity(idPath string) (crypto.PrivKey, error) {
if _, err := os.Stat(idPath); err == nil {
return ReadIdentity(idPath)
} else if os.IsNotExist(err) {
fmt.Printf("Generating peer identity in %s\n", idPath)
return GenerateIdentity(idPath)
} else {
return nil, err
}
}
// ReadIdentity reads a private key from the given path.
func ReadIdentity(path string) (crypto.PrivKey, error) {
bytes, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return crypto.UnmarshalPrivateKey(bytes)
}
// GenerateIdentity writes a new random private key to the given path.
func GenerateIdentity(path string) (crypto.PrivKey, error) {
privk, _, err := crypto.GenerateKeyPair(crypto.Ed25519, 0)
if err != nil {
return nil, err
}
bytes, err := crypto.MarshalPrivateKey(privk)
if err != nil {
return nil, err
}
err = os.WriteFile(path, bytes, 0400)
return privk, err
}