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
|
package key
import (
"encoding/hex"
"fmt"
"io"
"os"
)
// LoadKeypair reads the public and private keys from disc,
// or generates a new keypair if it does not already exist.
func LoadKeypair() (public, private [32]byte, err error) {
// Generate a keypair if it doesn't already exist.
err = generateIfNoExist()
if err != nil {
return
}
public, err = loadKey(pubKeyFile)
if err != nil {
return
}
private, err = loadKey(privKeyFile)
return
}
// LoadPublicKey reads the public key from disc, or generates a new keypair
// if it does not already exist.
func LoadPublicKey() ([32]byte, error) {
return loadKey(pubKeyFile)
}
// loadKey reads a key (public or private) from the specified file.
func loadKey(filename string) ([32]byte, error) {
// Open file.
f, err := os.Open(filename)
if err != nil {
return [32]byte{}, err
}
defer f.Close()
// Read key from file.
buf, err := io.ReadAll(f)
if err != nil {
return [32]byte{}, err
}
// Decode key.
var key [32]byte
if hex.DecodedLen(len(buf)) != len(key) {
return [32]byte{}, fmt.Errorf("malformed key: expected %d bytes; got %d",
len(key), hex.DecodedLen(len(buf)))
}
if _, err := hex.Decode(key[:], buf); err != nil {
return [32]byte{}, err
}
return key, nil
}
|