-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkeygenerator.go
62 lines (51 loc) · 1.12 KB
/
keygenerator.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
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
_ "crypto/x509/pkix"
"encoding/pem"
"fmt"
"io/ioutil"
_ "math/big"
"os"
)
func main() {
reader := rand.Reader
bitSize := 2048
key, err := rsa.GenerateKey(reader, bitSize)
checkError(err)
pubKey := key.PublicKey
savePrivateKey("private-key.pem", key)
savePublicKey("public-key.pem", pubKey)
}
func savePrivateKey(fileName string, key *rsa.PrivateKey) {
outFile, err := os.Create(fileName)
checkError(err)
defer outFile.Close()
privBytes := pem.EncodeToMemory(
&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
},
)
ioutil.WriteFile(fileName, privBytes, 0644)
}
func savePublicKey(fileName string, key rsa.PublicKey) {
outFile, err := os.Create(fileName)
checkError(err)
defer outFile.Close()
bytes, err := x509.MarshalPKIXPublicKey(&key)
checkError(err)
pubBytes := pem.EncodeToMemory(&pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: bytes,
})
ioutil.WriteFile(fileName, []byte(pubBytes), 0644)
}
func checkError(err error) {
if err != nil {
fmt.Println("Fatal error ", err.Error())
os.Exit(1)
}
}