Commit 1714ca89 authored by Sietse Ringers's avatar Sietse Ringers
Browse files

Add keygen command to scheme manager tool

parent 4b80f23e
......@@ -25,6 +25,19 @@ func AssertPathExists(paths ...string) error {
return nil
}
func AssertPathNotExists(paths ...string) error {
for _, p := range paths {
exist, err := PathExists(p)
if err != nil {
return err
}
if exist {
return errors.Errorf("Path %s exists but should not", p)
}
}
return nil
}
// PathExists checks if the specified path exists.
func PathExists(path string) (bool, error) {
_, err := os.Stat(path)
......
package cmd
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"os"
"io/ioutil"
"fmt"
"github.com/credentials/irmago/internal/fs"
"github.com/go-errors/errors"
"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
bts, err := x509.MarshalECPrivateKey(key)
if err != nil {
return err
}
pemEncoded := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: bts})
bts, err = x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil {
os.Exit(1)
}
pemEncodedPub := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: bts})
// 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() {
RootCmd.AddCommand(keygenCmd)
keygenCmd.Flags().StringP("privatekey", "s", "sk.pem", "filename for private key")
keygenCmd.Flags().StringP("publickey", "p", "pk.pem", "filename for public key")
}
......@@ -7,8 +7,6 @@ import (
"github.com/spf13/cobra"
)
var cfgFile string
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: "schememgr",
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment