-
Notifications
You must be signed in to change notification settings - Fork 0
/
keys.go
86 lines (73 loc) · 1.93 KB
/
keys.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
package entities
import (
"crypto/ed25519"
"crypto/rand"
"encoding/pem"
"strings"
"time"
"github.com/mikesmitty/edkey"
"github.com/teris-io/shortid"
"golang.org/x/crypto/ssh"
)
var (
KeyStatusNew = "NEW"
KeyStatusAdapting = "ADAPTING"
KeyStatusActive = "ACTIVE"
KeyStatusFailing = "FAILING"
KeyStatusDeleted = "DELETED"
)
type SSHKey struct {
ID string `json:"id"`
ProviderID string `json:"providerId"`
Name string `json:"name"`
Status string `json:"status"`
Fingerprint string `json:"fingerprint"`
Error string `json:"error"`
PrivateKey string `json:"privateKey"`
PublicKey string `json:"publicKey"`
Created time.Time `json:"created"`
Updated time.Time `json:"updated"`
}
func (k *SSHKey) NeedsAdapting() bool {
if k.Status == KeyStatusNew {
return true
}
return false
}
// GenerateKeyPair creates a SSH key pair (Ed25519).
func GenerateKeyPair() (*SSHKey, error) {
pubKey, privKey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, err
}
// Public key instance.
publicKeyInst, err := ssh.NewPublicKey(pubKey)
if err != nil {
return nil, err
}
id, err := shortid.Generate()
if err != nil {
return nil, err
}
now := time.Now()
// Serialize public key use in OpenSSH authorized_keys.
publicKey := ssh.MarshalAuthorizedKey(publicKeyInst)
// Fingerprint as unpadded base64 encoded sha256 hash.
// RFC4648 #section3-2 (unpadded base64 encoding)
fingerprint := ssh.FingerprintSHA256(publicKeyInst)
// Encode private key in PEM format.
privateKey := pem.EncodeToMemory(&pem.Block{
Type: "OPENSSH PRIVATE KEY",
Bytes: edkey.MarshalED25519PrivateKey(privKey),
})
return &SSHKey{
ID: id,
Name: id,
PrivateKey: string(privateKey),
PublicKey: strings.TrimRight(string(publicKey), "\n"),
Fingerprint: fingerprint,
Status: KeyStatusNew,
Created: now,
Updated: now,
}, nil
}