-
Notifications
You must be signed in to change notification settings - Fork 0
/
sshkey.go
87 lines (72 loc) · 2.08 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
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
81
82
83
84
85
86
87
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"log"
"os"
gossh "golang.org/x/crypto/ssh"
)
func generateRSA4096Key(filename string) error {
privateKey, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
return fmt.Errorf("%s (RSA %s): %v", l("HOSTKEYGENERR"), filename, err)
}
privateKeyFile, err := os.Create(filename)
if err != nil {
return fmt.Errorf("%s (RSA %s): %v", l("HOSTKEYGENERR"), filename, err)
}
defer privateKeyFile.Close()
privateKeyPEM := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
}
if err := pem.Encode(privateKeyFile, privateKeyPEM); err != nil {
return fmt.Errorf("%s (RSA %s): %v", l("HOSTKEYGENERR"), filename, err)
}
return nil
}
func generateECDSAKey(filename string) error {
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return fmt.Errorf("%s (ECDSA %s): %v", l("HOSTKEYGENERR"), filename, err)
}
privateKeyFile, err := os.Create(filename)
if err != nil {
return fmt.Errorf("%s (ECDSA %s): %v", l("HOSTKEYGENERR"), filename, err)
}
defer privateKeyFile.Close()
privateKeyBytes, err := x509.MarshalECPrivateKey(privateKey)
if err != nil {
return fmt.Errorf("%s (ECDSA %s): %v", l("HOSTKEYGENERR"), filename, err)
}
privateKeyPEM := &pem.Block{
Type: "EC PRIVATE KEY",
Bytes: privateKeyBytes,
}
if err := pem.Encode(privateKeyFile, privateKeyPEM); err != nil {
return fmt.Errorf("%s (ECDSA %s): %v", l("HOSTKEYGENERR"), filename, err)
}
return nil
}
func loadOrGenerateSSHKey(filename string) (gossh.Signer, error) {
if _, err := os.Stat(filename); os.IsNotExist(err) {
log.Println(l("GENNEWKEY"), filename)
if err := generateECDSAKey(filename); err != nil {
return nil, err
}
}
privateBytes, err := os.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("%s: %v", l("PRIKEYLOADERR"), err)
}
private, err := gossh.ParsePrivateKey(privateBytes)
if err != nil {
return nil, fmt.Errorf("%s: %v", l("PRIKEYPARSEERR"), err)
}
return private, nil
}