forked from goodrain/rainbond
/
ssh.go
36 lines (28 loc) · 840 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
36
package util
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"golang.org/x/crypto/ssh"
)
// GenOpenSSHKeyPair make a pair of private and public keys for SSH access.
// Private Key generated is PEM encoded
// Public key is encoded in the format for inclusion in an OpenSSH authorized_keys file.
func GenOpenSSHKeyPair() ([]byte, []byte, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, err
}
privateKeyPEM := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
}
rsaSSHPriKeyBytes := pem.EncodeToMemory(privateKeyPEM)
pub, err := ssh.NewPublicKey(&privateKey.PublicKey)
if err != nil {
return nil, nil, err
}
rsaSSHPubKeyBytes := ssh.MarshalAuthorizedKey(pub)
return rsaSSHPriKeyBytes, rsaSSHPubKeyBytes, nil
}