forked from tw4dl/libretto
/
keys.go
115 lines (96 loc) · 2.3 KB
/
keys.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// Copyright 2015 Apcera Inc. All rights reserved.
package ssh
import (
"crypto/md5"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"os"
"runtime"
gossh "github.com/apcera/libretto/Godeps/_workspace/src/golang.org/x/crypto/ssh"
)
// NewKeyPair generates a new SSH keypair. This will return a private & public key encoded as DER.
func NewKeyPair() (keyPair *KeyPair, err error) {
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, ErrKeyGeneration
}
if err := priv.Validate(); err != nil {
return nil, ErrValidation
}
privDer := x509.MarshalPKCS1PrivateKey(priv)
privateKey := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Headers: nil, Bytes: privDer})
pubSSH, err := gossh.NewPublicKey(&priv.PublicKey)
if err != nil {
return nil, ErrPublicKey
}
return &KeyPair{
PrivateKey: privateKey,
PublicKey: gossh.MarshalAuthorizedKey(pubSSH),
}, nil
}
// KeyPair represents a Public and Private keypair.
type KeyPair struct {
PrivateKey []byte
PublicKey []byte
}
// ReadFromFile reads a keypair from files.
func (kp *KeyPair) ReadFromFile(privateKeyPath string, publicKeyPath string) error {
b, err := ioutil.ReadFile(privateKeyPath)
if err != nil {
return err
}
kp.PrivateKey = b
b, err = ioutil.ReadFile(publicKeyPath)
if err != nil {
return err
}
kp.PublicKey = b
return nil
}
// WriteToFile writes a keypair to files
func (kp *KeyPair) WriteToFile(privateKeyPath string, publicKeyPath string) error {
files := []struct {
File string
Type string
Value []byte
}{
{
File: privateKeyPath,
Value: kp.PrivateKey,
},
{
File: publicKeyPath,
Value: kp.PublicKey,
},
}
for _, v := range files {
f, err := os.Create(v.File)
if err != nil {
return ErrUnableToWriteFile
}
if _, err := f.Write(v.Value); err != nil {
return ErrUnableToWriteFile
}
// windows does not support chmod
switch runtime.GOOS {
case "darwin", "linux":
if err := f.Chmod(0600); err != nil {
return err
}
}
}
return nil
}
// Fingerprint calculates the fingerprint of the public key
func (kp *KeyPair) Fingerprint() string {
b, _ := base64.StdEncoding.DecodeString(string(kp.PublicKey))
h := md5.New()
io.WriteString(h, string(b))
return fmt.Sprintf("%x", h.Sum(nil))
}