-
Notifications
You must be signed in to change notification settings - Fork 23
/
rsa.go
87 lines (68 loc) · 1.74 KB
/
rsa.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
75
76
77
78
79
80
81
82
83
84
85
86
87
package keys
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"code.cloudfoundry.org/diego-ssh/helpers"
"golang.org/x/crypto/ssh"
)
//go:generate counterfeiter -o fake_keys/fake_key_pair.go . KeyPair
type KeyPair interface {
PrivateKey() ssh.Signer
PEMEncodedPrivateKey() string
PublicKey() ssh.PublicKey
Fingerprint() string
AuthorizedKey() string
}
//go:generate counterfeiter -o fake_keys/fake_ssh_key_factory.go . SSHKeyFactory
type SSHKeyFactory interface {
NewKeyPair(bits int) (KeyPair, error)
}
var RSAKeyPairFactory SSHKeyFactory = &keyPairFactory{}
type keyPairFactory struct{}
func (r *keyPairFactory) NewKeyPair(bits int) (KeyPair, error) {
return newRSA(bits)
}
type rsaKeyPair struct {
encodedPrivateKey string
privateKey ssh.Signer
}
func newRSA(bits int) (KeyPair, error) {
key, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return nil, err
}
err = key.Validate()
if err != nil {
return nil, err
}
encodedPrivateKey := pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: x509.MarshalPKCS1PrivateKey(key),
})
privateKey, err := ssh.ParsePrivateKey(encodedPrivateKey)
if err != nil {
return nil, err
}
return &rsaKeyPair{
encodedPrivateKey: string(encodedPrivateKey),
privateKey: privateKey,
}, nil
}
func (k *rsaKeyPair) PrivateKey() ssh.Signer {
return k.privateKey
}
func (k *rsaKeyPair) PEMEncodedPrivateKey() string {
return k.encodedPrivateKey
}
func (k *rsaKeyPair) PublicKey() ssh.PublicKey {
return k.privateKey.PublicKey()
}
func (k *rsaKeyPair) Fingerprint() string {
return helpers.MD5Fingerprint(k.PublicKey())
}
func (k *rsaKeyPair) AuthorizedKey() string {
return string(ssh.MarshalAuthorizedKey(k.PublicKey()))
}