-
Notifications
You must be signed in to change notification settings - Fork 0
/
sshkey.go
48 lines (35 loc) · 1.17 KB
/
sshkey.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
package main
import (
"fmt"
"os"
"os/exec"
"path"
)
const sshKeyType = "ed25519"
func GenerateSSHKeypair(tmpDir string) (string, string, error) {
DebugLogger.Printf("generating SSH keypair in %s", tmpDir)
privateKeyPath := path.Join(tmpDir, "id_"+sshKeyType)
publicKeyPath := privateKeyPath + ".pub"
cmd := exec.Command("ssh-keygen", "-q", "-t", sshKeyType, "-f", privateKeyPath, "-N", "")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return "", "", fmt.Errorf("failed to generate keypair using ssh-keygen: %w", err)
}
publicKeyBytes, err := os.ReadFile(publicKeyPath)
if err != nil {
return "", "", fmt.Errorf("failed to read generated public key file: %w", err)
}
publicKey := string(publicKeyBytes)
return privateKeyPath, publicKey, nil
}
func GetSSHPublicKey(privateKeyPath string) (string, error) {
DebugLogger.Printf("getting public key from %s", privateKeyPath)
cmd := exec.Command("ssh-keygen", "-y", "-f", privateKeyPath)
outputBytes, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("failed to get public key using ssh-keygen: %w", err)
}
publicKey := string(outputBytes)
return publicKey, nil
}