keygen.go 1.85 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
package cmd

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"io/ioutil"

	"fmt"

	"github.com/go-errors/errors"
12
	"github.com/privacybydesign/gabi/signed"
13
	"github.com/privacybydesign/irmago/internal/fs"
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
	"github.com/spf13/cobra"
)

// keygenCmd represents the keygen command
var keygenCmd = &cobra.Command{
	Use:   "keygen",
	Short: "Generate ECDSA private/public keypair",
	Long:  `Generate an ECDSA private/public keypair suitable for signing IRMA scheme managers.`,
	RunE: func(cmd *cobra.Command, args []string) error {
		skfile, err := cmd.Flags().GetString("privatekey")
		if err != nil {
			return err
		}
		pkfile, err := cmd.Flags().GetString("publickey")
		if err != nil {
			return err
		}

		// For safety we enforce that we never overwrite a file
		if err := fs.AssertPathNotExists(skfile); err != nil {
			return errors.Errorf("File %s already exists, not overwriting", skfile)
		}
		if err := fs.AssertPathNotExists(pkfile); err != nil {
			return errors.Errorf("File %s already exists, not overwriting", pkfile)
		}

		// Generate keys
		key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
		if err != nil {
			return err
		}

		// Marshal keys
47
		pemEncoded, err := signed.MarshalPemPrivateKey(key)
48
49
50
		if err != nil {
			return err
		}
51
		pemEncodedPub, err := signed.MarshalPemPublicKey(&key.PublicKey)
52
		if err != nil {
53
			return err
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
		}

		// Save keys
		if err = ioutil.WriteFile(skfile, pemEncoded, 0600); err != nil {
			return err
		}
		fmt.Println("Private key written at", skfile)
		if err = ioutil.WriteFile(pkfile, pemEncodedPub, 0644); err != nil {
			return err
		}
		fmt.Println("Public key written at", pkfile)

		return nil
	},
}

func init() {
71
	schemeCmd.AddCommand(keygenCmd)
72
73
74
	keygenCmd.Flags().StringP("privatekey", "s", "sk.pem", "filename for private key")
	keygenCmd.Flags().StringP("publickey", "p", "pk.pem", "filename for public key")
}