aboutsummaryrefslogtreecommitdiff
path: root/client/keys.go
blob: d2f14f7a3e1afd28b52d70548e8bbc9734c1aa6b (plain)
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
package main

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/rsa"
	"fmt"

	"golang.org/x/crypto/ssh"
)

type key interface{}
type keyfunc func(int) (key, ssh.PublicKey, error)

var (
	keytypes = map[string]keyfunc{
		"rsa":   generateRSAKey,
		"ecdsa": generateECDSAKey,
	}
)

func generateRSAKey(bits int) (key, ssh.PublicKey, error) {
	k, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return nil, nil, err
	}
	pub, err := ssh.NewPublicKey(&k.PublicKey)
	if err != nil {
		return nil, nil, err
	}
	return k, pub, nil
}

func generateECDSAKey(bits int) (key, ssh.PublicKey, error) {
	var curve elliptic.Curve
	switch bits {
	case 256:
		curve = elliptic.P256()
	case 384:
		curve = elliptic.P384()
	case 521:
		curve = elliptic.P521()
	default:
		return nil, nil, fmt.Errorf("Unsupported key size. Valid sizes are '256', '384', '521'")
	}
	k, err := ecdsa.GenerateKey(curve, rand.Reader)
	if err != nil {
		return nil, nil, err
	}
	pub, err := ssh.NewPublicKey(&k.PublicKey)
	if err != nil {
		return nil, nil, err
	}
	return k, pub, nil
}

func generateKey(keytype string, bits int) (key, ssh.PublicKey, error) {
	f, ok := keytypes[keytype]
	if !ok {
		var valid []string
		for k := range keytypes {
			valid = append(valid, k)
		}
		return nil, nil, fmt.Errorf("Unsupported key type %s. Valid choices are %s", keytype, valid)
	}
	return f(bits)
}