aboutsummaryrefslogtreecommitdiffstats
path: root/key/generate.go
blob: bb4a61e9bf6211aabfb9f34a7303930202629b57 (plain) (blame)
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
78
package key

import (
	crypto_rand "crypto/rand"
	"encoding/hex"
	"fmt"
	"golang.org/x/crypto/nacl/box"
	"os"

	"git.samanthony.xyz/hose/util"
)

// generateBoxKeypair generates a new public/private keypair for NaCl box
// (encryption/decryption) operations.  It stores the private key in the private box
// key file and the public box key in the public key file.  If either of the key files
// already exist, they will not be overwritten; instead an error will be returned.
func generateBoxKeypair() error {
	util.Logf("generating new encryption/decryption keypair...")

	// Create public key file.
	pubFile, err := createFile(boxPubKeyFile, pubFileMode)
	if err != nil {
		return err
	}
	defer pubFile.Close()

	// Create private key file.
	privFile, err := createFile(boxPrivKeyFile, privFileMode)
	if err != nil {
		pubFile.Close()
		_ = os.Remove(boxPubKeyFile)
		return err
	}
	defer privFile.Close()

	// Generate keypair.
	pubkey, privkey, err := box.GenerateKey(crypto_rand.Reader)
	if err != nil {
		return err
	}

	// Write keypair to files.
	buf := make([]byte, hex.EncodedLen(len(*pubkey)))
	hex.Encode(buf, (*pubkey)[:])
	if _, err := pubFile.Write(buf); err != nil {
		return err
	}
	buf = make([]byte, hex.EncodedLen(len(*privkey)))
	hex.Encode(buf, (*privkey)[:])
	if _, err := privFile.Write(buf); err != nil {
		return err
	}

	return nil
}

// generateBoxKeypairIfNotExist generates a NaCal box keypair if it doesn't already exist.
func generateBoxKeypairIfNotExist() error {
	pubExists, err := fileExists(boxPubKeyFile)
	if err != nil {
		return err
	}
	privExists, err := fileExists(boxPrivKeyFile)
	if err != nil {
		return err
	}

	if pubExists && privExists {
		// Keypair already exists.
		return nil
	} else if pubExists && !privExists {
		return fmt.Errorf("found public key file but not private key file")
	} else if privExists && !pubExists {
		return fmt.Errorf("found private key file but not public key file")
	}
	// Neither public nor private key file exists; generate new keypair.
	return generateBoxKeypair()
}