Skip to content

Commit

Permalink
#5 Put RSA key generation into separate function
Browse files Browse the repository at this point in the history
  • Loading branch information
quapka committed Mar 8, 2019
1 parent 4df2ee9 commit 36c4c3a
Showing 1 changed file with 32 additions and 24 deletions.
56 changes: 32 additions & 24 deletions gen-keys/generate_keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ import (
"crypto/rand"
"crypto/rsa"
"fmt"
"io"
"log"
"os"
"strconv"
"time"
)

func main() {
var err error

algorithm := os.Args[1]
arg2 := os.Args[2]
Expand Down Expand Up @@ -44,34 +46,28 @@ func main() {
log.Fatal(err)
}

// TODO rand.Redaer is global and maybe we don't need to pass it along
// but just call it, when it is needed
reader := rand.Reader
dataRow := ""

for id := 0; id < keyCount; id++ {
dataRow = fmt.Sprintf("%d;", id)
var dataRow string = ""
var data string = ""

if algorithm == "rsa" {
start := time.Now()
key, rsaerr := rsa.GenerateKey(reader, bitSize)
end := time.Now()
t1 := end.Sub(start)

checkError(rsaerr)

publicKey := key.PublicKey

var n = publicKey.N
var e = publicKey.E
var d = key.D
var p = key.Primes[0]
var q = key.Primes[1]

dataRow += fmt.Sprintf("%x;%x;%x;%x;%x;%d;\n", n, e, d, p, q, t1)
idPrefix := fmt.Sprintf("%d;", id)

if algorithm == "rsa" {
data, err = getRSAData(reader, bitSize)
if err != nil {
// fmt.Printf("Got errorneous data: %s\n", data)
log.Fatal(err)
}
} else if algorithm == "ecc" {
log.Fatal("Not implemented yet.")
log.Fatal("Generating ECC keys is not implemented yet.")
}

dataRow = idPrefix + data + "\n"

// Write keys
if _, err := f.Write([]byte(dataRow)); err != nil {
log.Fatal(err)
Expand All @@ -82,12 +78,24 @@ func main() {
if err := f.Close(); err != nil {
log.Fatal(err)
}

}

func checkError(err error) {
func getRSAData(reader io.Reader, bitSize int) (data string, err error) {
start := time.Now()
key, err := rsa.GenerateKey(reader, bitSize)
end := time.Now()
t1 := end.Sub(start)

if err != nil {
fmt.Println("Fatal error ", err.Error())
os.Exit(1)
fmt.Println("We got a problem")
return "", err
}

n := key.PublicKey.N
e := key.PublicKey.E
d := key.D
p := key.Primes[0]
q := key.Primes[1]

return fmt.Sprintf("%x;%x;%x;%x;%x;%d;", n, e, d, p, q, t1), nil
}

0 comments on commit 36c4c3a

Please sign in to comment.