-
Notifications
You must be signed in to change notification settings - Fork 7
/
key.go
65 lines (51 loc) · 1.25 KB
/
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
package ssh
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
sshlib "golang.org/x/crypto/ssh"
)
type CryptoBytes []byte
func (c *CryptoBytes) UnmarshalYAML(unmarshal func(interface{}) error) error {
var data string
err := unmarshal(&data)
if err != nil {
return err
}
*c = []byte(data)
return nil
}
func (c CryptoBytes) MarshalYAML() (interface{}, error) {
return string(c), nil
}
type RsaKeyPair struct {
PrivateKey CryptoBytes `json:"privateKey" yaml:"privateKey"`
PublicKey CryptoBytes `json:"publicKey" yaml:"publicKey"`
}
func (r RsaKeyPair) Empty() bool {
return len(r.PrivateKey) == 0 && len(r.PublicKey) == 0
}
func GenerateRsaKeyPair() (RsaKeyPair, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
return RsaKeyPair{}, err
}
err = privateKey.Validate()
if err != nil {
return RsaKeyPair{}, err
}
publicRsaKey, err := sshlib.NewPublicKey(&privateKey.PublicKey)
if err != nil {
return RsaKeyPair{}, err
}
pubKeyBytes := sshlib.MarshalAuthorizedKey(publicRsaKey)
privateKeyPem := pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
})
return RsaKeyPair{
PrivateKey: privateKeyPem,
PublicKey: pubKeyBytes,
}, nil
}