Skip to content

Commit

Permalink
feat(rsa): generate RSA if it doesnt exists
Browse files Browse the repository at this point in the history
  • Loading branch information
jkuri committed Apr 16, 2018
1 parent 9627052 commit 421c7e8
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
build/
id_rsa
id_rsa.pub
.DS_Store

4 changes: 4 additions & 0 deletions cmd/vexd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ func main() {
*httplistenaddr = "0.0.0.0:2000"
}

if _, err := os.Stat(*privatekeyfile); os.IsNotExist(err) {
vexserver.GenerateRSA()
}

config := &vexserver.Config{
Domain: *domain,
PrivateKeyFile: *privatekeyfile,
Expand Down
73 changes: 73 additions & 0 deletions server/rsa.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package vexserver

import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/asn1"
"encoding/gob"
"encoding/pem"
"fmt"
"os"
)

func GenerateRSA() {
reader := rand.Reader
bitSize := 2048

key, err := rsa.GenerateKey(reader, bitSize)
checkError(err)

publicKey := key.PublicKey

savePEMKey("id_rsa", key)
savePublicPEMKey("id_rsa.pub", publicKey)
}

func saveGobKey(fileName string, key interface{}) {
outFile, err := os.Create(fileName)
checkError(err)
defer outFile.Close()

encoder := gob.NewEncoder(outFile)
err = encoder.Encode(key)
checkError(err)
}

func savePEMKey(fileName string, key *rsa.PrivateKey) {
outFile, err := os.Create(fileName)
checkError(err)
defer outFile.Close()

var privateKey = &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
}

err = pem.Encode(outFile, privateKey)
checkError(err)
}

func savePublicPEMKey(fileName string, pubkey rsa.PublicKey) {
asn1Bytes, err := asn1.Marshal(pubkey)
checkError(err)

var pemkey = &pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: asn1Bytes,
}

pemfile, err := os.Create(fileName)
checkError(err)
defer pemfile.Close()

err = pem.Encode(pemfile, pemkey)
checkError(err)
}

func checkError(err error) {
if err != nil {
fmt.Println("Fatal error ", err.Error())
os.Exit(1)
}
}

0 comments on commit 421c7e8

Please sign in to comment.