-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthkeys.go
More file actions
56 lines (42 loc) · 1020 Bytes
/
authkeys.go
File metadata and controls
56 lines (42 loc) · 1020 Bytes
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
package main
import (
"crypto/rand"
"crypto/rsa"
"strings"
"golang.org/x/crypto/ssh"
)
func generateSSHKeypair(bitSize int) (ssh.Signer, string, error) {
privKey, err := generatePrivateKey(bitSize)
if err != nil {
return nil, "", err
}
signer, err := ssh.NewSignerFromKey(privKey)
if err != nil {
return nil, "", err
}
pubKey, err := generatePublicKey(&privKey.PublicKey)
if err != nil {
return nil, "", err
}
return signer, pubKey, nil
}
func generatePrivateKey(bitSize int) (*rsa.PrivateKey, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, bitSize)
if err != nil {
return nil, err
}
err = privateKey.Validate()
if err != nil {
return nil, err
}
return privateKey, nil
}
func generatePublicKey(pubKey *rsa.PublicKey) (string, error) {
publicRsaKey, err := ssh.NewPublicKey(pubKey)
if err != nil {
return "", err
}
pubKeyBytes := ssh.MarshalAuthorizedKey(publicRsaKey)
pubKeyString := strings.TrimSuffix(string(pubKeyBytes), "\n")
return pubKeyString, nil
}