/
create_ssh_key.go
80 lines (64 loc) · 1.43 KB
/
create_ssh_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
75
76
77
78
79
80
package infrastructure
import (
"context"
"crypto/ed25519"
"crypto/rand"
"encoding/pem"
"github.com/hetznercloud/hcloud-go/hcloud"
"github.com/mikesmitty/edkey"
"golang.org/x/crypto/ssh"
)
type SSHKey struct {
ID int `json:"id"`
Name string `json:"name"`
PEMContent string `json:"pem_content"`
}
func CreateSSHKey(
hetznerClient *hcloud.Client,
name string,
) (returnedSSHKey *SSHKey, returnedError error) {
publicKey, privateKey, err := generateEd25519Keys()
if err != nil {
return nil, err
}
createSSHKeyResp, _, err := hetznerClient.SSHKey.Create(
context.TODO(),
hcloud.SSHKeyCreateOpts{
Name: name,
PublicKey: publicKey,
},
)
if err != nil {
returnedError = err
return
}
returnedSSHKey = &SSHKey{
ID: createSSHKeyResp.ID,
Name: createSSHKeyResp.Name,
PEMContent: privateKey,
}
return
}
func generateEd25519Keys() (
returnedPubkey string,
returnedPrivateKey string,
returnedError error,
) {
pubKey, privKey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
returnedError = err
return
}
publicKey, err := ssh.NewPublicKey(pubKey)
if err != nil {
returnedError = err
return
}
pemKey := &pem.Block{
Type: "OPENSSH PRIVATE KEY",
Bytes: edkey.MarshalED25519PrivateKey(privKey),
}
privateKey := pem.EncodeToMemory(pemKey)
authorizedKey := ssh.MarshalAuthorizedKey(publicKey)
return string(authorizedKey), string(privateKey), nil
}