forked from mouuff/go-rocket-update
/
keygen.go
74 lines (57 loc) · 1.56 KB
/
keygen.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
71
72
73
74
package main
import (
"errors"
"flag"
"io/ioutil"
"log"
"github.com/mouuff/go-rocket-update/internal/crypto"
"github.com/mouuff/go-rocket-update/internal/fileio"
)
// Keygen describes the keygen subcommand
// this command is used to generate a private and a public key
type Keygen struct {
flagSet *flag.FlagSet
keyName string
}
// Name gets the name of the command
func (cmd *Keygen) Name() string {
return "keygen"
}
// Init initializes the command
func (cmd *Keygen) Init(args []string) error {
cmd.flagSet = flag.NewFlagSet(cmd.Name(), flag.ExitOnError)
cmd.flagSet.StringVar(&cmd.keyName, "name", "id_rsa", "name of the key to generate")
return cmd.flagSet.Parse(args)
}
// Run runs the command
func (cmd *Keygen) Run() error {
privateKeyPath := cmd.keyName
publicKeyPath := cmd.keyName + ".pub"
if fileio.FileExists(privateKeyPath) {
return errors.New("Key '" + privateKeyPath + "' already exists")
}
if fileio.FileExists(publicKeyPath) {
return errors.New("Key '" + publicKeyPath + "' already exists")
}
log.Println("Generating keys...")
priv, err := crypto.GeneratePrivateKey()
if err != nil {
return err
}
privPem := crypto.ExportPrivateKeyAsPem(priv)
err = ioutil.WriteFile(privateKeyPath, privPem, 0600)
if err != nil {
return err
}
log.Println("Created private key: " + privateKeyPath)
pubPem, err := crypto.ExportPublicKeyAsPem(&priv.PublicKey)
if err != nil {
return err
}
err = ioutil.WriteFile(publicKeyPath, pubPem, 0644)
if err != nil {
return err
}
log.Println("Created public key: " + publicKeyPath)
return nil
}