This repository has been archived by the owner on May 18, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
keypair.go
110 lines (90 loc) · 2.13 KB
/
keypair.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package auth
import (
"bufio"
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"github.com/sean-/seed"
"golang.org/x/crypto/ssh"
)
func init() {
seed.MustInit()
}
type KeyPair struct {
PublicKey ssh.PublicKey
PrivateKey *rsa.PrivateKey
FingerprintMD5 string
publicKeyBase64 string
privateKeyPEM string
}
func NewKeyPair(bits int) (*KeyPair, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return nil, err
}
sshPublicKey, err := ssh.NewPublicKey(&privateKey.PublicKey)
if err != nil {
return nil, err
}
fingerprintMD5 := ssh.FingerprintLegacyMD5(sshPublicKey)
return &KeyPair{
PrivateKey: privateKey,
PublicKey: sshPublicKey,
FingerprintMD5: fingerprintMD5,
}, nil
}
func DecodeKeyPair(material string) (*KeyPair, error) {
privateKey, err := x509.ParsePKCS1PrivateKey([]byte(material))
if err != nil {
return nil, err
}
sshPublicKey, err := ssh.NewPublicKey(&privateKey.PublicKey)
if err != nil {
return nil, err
}
fingerprintMD5 := ssh.FingerprintLegacyMD5(sshPublicKey)
return &KeyPair{
PrivateKey: privateKey,
PublicKey: sshPublicKey,
FingerprintMD5: fingerprintMD5,
}, nil
}
func (kp *KeyPair) genPrivateKeyPEM() error {
privateKeyBuff := &bytes.Buffer{}
privatePEM := bufio.NewWriter(privateKeyBuff)
privatePEMBlock := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(kp.PrivateKey),
}
if err := pem.Encode(privatePEM, privatePEMBlock); err != nil {
return err
}
if err := privatePEM.Flush(); err != nil {
return err
}
kp.privateKeyPEM = fmt.Sprintf("%s", privateKeyBuff)
return nil
}
func (kp *KeyPair) PrivateKeyPEM() string {
if kp.privateKeyPEM == "" {
err := kp.genPrivateKeyPEM()
if err != nil {
return ""
}
}
return kp.privateKeyPEM
}
func (kp *KeyPair) genPublicKeyBase64() {
publicKeyBase := base64.StdEncoding.EncodeToString(kp.PublicKey.Marshal())
kp.publicKeyBase64 = "ssh-rsa " + string(publicKeyBase)
}
func (kp *KeyPair) PublicKeyBase64() string {
if kp.publicKeyBase64 == "" {
kp.genPublicKeyBase64()
}
return kp.publicKeyBase64
}