-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
98 lines (84 loc) · 1.73 KB
/
crypto.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
package door_comms
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/asn1"
"encoding/pem"
"io/ioutil"
"os"
)
func GetKeys() (*rsa.PrivateKey, *rsa.PublicKey, error) {
if _, err := os.Stat("private.pem"); err == nil {
key, err := loadPEMKey("private.pem")
if err != nil {
return nil, nil, err
}
return key, &key.PublicKey, nil
} else {
reader := rand.Reader
bitSize := 2048
key, err := rsa.GenerateKey(reader, bitSize)
if err != nil {
return nil, nil, err
}
publicKey := key.PublicKey
err = savePEMKey("private.pem", key)
if err != nil {
return nil, nil, err
}
err = savePublicPEMKey("public.pem", publicKey)
if err != nil {
return nil, nil, err
}
return key, &publicKey, nil
}
}
func loadPEMKey(fileName string) (*rsa.PrivateKey, error) {
outFile, err := ioutil.ReadFile(fileName)
if err != nil {
return nil, err
}
block, _ := pem.Decode(outFile)
key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return key, nil
}
func savePEMKey(fileName string, key *rsa.PrivateKey) error {
outFile, err := os.Create(fileName)
if err != nil {
return err
}
defer outFile.Close()
var privateKey = &pem.Block{
Type: "PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
}
err = pem.Encode(outFile, privateKey)
if err != nil {
return err
}
return nil
}
func savePublicPEMKey(fileName string, pubkey rsa.PublicKey) error {
asn1Bytes, err := asn1.Marshal(pubkey)
if err != nil {
return err
}
var pemkey = &pem.Block{
Type: "PUBLIC KEY",
Bytes: asn1Bytes,
}
pemfile, err := os.Create(fileName)
if err != nil {
return err
}
defer pemfile.Close()
err = pem.Encode(pemfile, pemkey)
if err != nil {
return err
}
return nil
}