forked from EngineerBetter/concourse-up
/
ssh.go
35 lines (28 loc) · 851 Bytes
/
ssh.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
package util
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"bytes"
"golang.org/x/crypto/ssh"
)
// GenerateSSHKeyPair generates a new ssh public key pair
// http://stackoverflow.com/questions/21151714/go-generate-an-ssh-public-key
func GenerateSSHKeyPair() ([]byte, []byte, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, err
}
privateKeyBuffer := bytes.NewBuffer(nil)
privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}
if err = pem.Encode(privateKeyBuffer, privateKeyPEM); err != nil {
return nil, nil, err
}
// generate and write public key
pub, err := ssh.NewPublicKey(&privateKey.PublicKey)
if err != nil {
return nil, nil, err
}
return privateKeyBuffer.Bytes(), ssh.MarshalAuthorizedKey(pub), nil
}