forked from nanobox-io/golang-ssh
-
Notifications
You must be signed in to change notification settings - Fork 1
/
key.go
74 lines (65 loc) · 1.85 KB
/
key.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
package ssh
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"os"
"github.com/jcelliott/lumber"
"golang.org/x/crypto/ssh"
)
// GetKeyPair will attempt to get the keypair from a file and will fail back
// to generating a new set and saving it to the file. Returns pub, priv, err
func GetKeyPair(file string) (string, string, error) {
// read keys from file
_, err := os.Stat(file)
if err == nil {
priv, err := ioutil.ReadFile(file)
if err != nil {
lumber.Debug("Failed to read file - %s", err)
goto genKeys
}
pub, err := ioutil.ReadFile(file + ".pub")
if err != nil {
lumber.Debug("Failed to read pub file - %s", err)
goto genKeys
}
return string(pub), string(priv), nil
}
// generate keys and save to file
genKeys:
pub, priv, err := GenKeyPair()
err = ioutil.WriteFile(file, []byte(priv), 0600)
if err != nil {
return "", "", fmt.Errorf("Failed to write file - %s", err)
}
err = ioutil.WriteFile(file+".pub", []byte(pub), 0644)
if err != nil {
return "", "", fmt.Errorf("Failed to write pub file - %s", err)
}
return pub, priv, nil
}
// GenKeyPair make a pair of public and private keys for SSH access.
// Public key is encoded in the format for inclusion in an OpenSSH authorized_keys file.
// Private Key generated is PEM encoded
func GenKeyPair() (string, string, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return "", "", err
}
privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}
var private bytes.Buffer
if err := pem.Encode(&private, privateKeyPEM); err != nil {
return "", "", err
}
// generate public key
pub, err := ssh.NewPublicKey(&privateKey.PublicKey)
if err != nil {
return "", "", err
}
public := ssh.MarshalAuthorizedKey(pub)
return string(public), private.String(), nil
}