Skip to content

Commit 421c7e8

Browse files
committed
feat(rsa): generate RSA if it doesnt exists
1 parent 9627052 commit 421c7e8

File tree

3 files changed

+78
-0
lines changed

3 files changed

+78
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
build/
22
id_rsa
3+
id_rsa.pub
34
.DS_Store
45

cmd/vexd/main.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,10 @@ func main() {
7070
*httplistenaddr = "0.0.0.0:2000"
7171
}
7272

73+
if _, err := os.Stat(*privatekeyfile); os.IsNotExist(err) {
74+
vexserver.GenerateRSA()
75+
}
76+
7377
config := &vexserver.Config{
7478
Domain: *domain,
7579
PrivateKeyFile: *privatekeyfile,

server/rsa.go

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package vexserver
2+
3+
import (
4+
"crypto/rand"
5+
"crypto/rsa"
6+
"crypto/x509"
7+
"encoding/asn1"
8+
"encoding/gob"
9+
"encoding/pem"
10+
"fmt"
11+
"os"
12+
)
13+
14+
func GenerateRSA() {
15+
reader := rand.Reader
16+
bitSize := 2048
17+
18+
key, err := rsa.GenerateKey(reader, bitSize)
19+
checkError(err)
20+
21+
publicKey := key.PublicKey
22+
23+
savePEMKey("id_rsa", key)
24+
savePublicPEMKey("id_rsa.pub", publicKey)
25+
}
26+
27+
func saveGobKey(fileName string, key interface{}) {
28+
outFile, err := os.Create(fileName)
29+
checkError(err)
30+
defer outFile.Close()
31+
32+
encoder := gob.NewEncoder(outFile)
33+
err = encoder.Encode(key)
34+
checkError(err)
35+
}
36+
37+
func savePEMKey(fileName string, key *rsa.PrivateKey) {
38+
outFile, err := os.Create(fileName)
39+
checkError(err)
40+
defer outFile.Close()
41+
42+
var privateKey = &pem.Block{
43+
Type: "RSA PRIVATE KEY",
44+
Bytes: x509.MarshalPKCS1PrivateKey(key),
45+
}
46+
47+
err = pem.Encode(outFile, privateKey)
48+
checkError(err)
49+
}
50+
51+
func savePublicPEMKey(fileName string, pubkey rsa.PublicKey) {
52+
asn1Bytes, err := asn1.Marshal(pubkey)
53+
checkError(err)
54+
55+
var pemkey = &pem.Block{
56+
Type: "RSA PUBLIC KEY",
57+
Bytes: asn1Bytes,
58+
}
59+
60+
pemfile, err := os.Create(fileName)
61+
checkError(err)
62+
defer pemfile.Close()
63+
64+
err = pem.Encode(pemfile, pemkey)
65+
checkError(err)
66+
}
67+
68+
func checkError(err error) {
69+
if err != nil {
70+
fmt.Println("Fatal error ", err.Error())
71+
os.Exit(1)
72+
}
73+
}

0 commit comments

Comments
 (0)