Gentry Rolofson
Gentry Rolofson

Reputation: 51

Storing and retrieving RSA encryption key

I am trying to build an API, but to secure it properly I believe I need to go with RSA encryption for a private key stored on my server and a public key for the client. I have stored the generated private key into a JSON file, I plan to store on my server but to write to JSON, I needed to convert the type too []byte. Now when I try to retrieve the private key to generate a public key, but it will not let me use type bytes for *Publickey The only other way I can think of to accomplish this goal is to seed the random number generator, so I can have the seed a secret on my server and then my private key should always generate to the same thing, any help this this would be great.

package main

import (
    "bytes"
    "crypto/rand"
    "crypto/rsa"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    mimicPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    buf := new(bytes.Buffer)
    json.NewEncoder(buf).Encode(mimicPrivateKey)
    secrets, _ := os.OpenFile("secrets.json",    os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
    // Close the secrets file when the surrounding function exists

    secrets.WriteString(buf.String())
    secrets.Close()

    secrets, _ = os.OpenFile("secrets.json", os.O_RDWR, 0666)
    serverKey, _ := ioutil.ReadAll(secrets)
    if serverKey != nil {
        fmt.Println("can not open key")
    }

    serverKeyPublic := &serverKey.PublicKey
}

Upvotes: 1

Views: 2364

Answers (1)

user6169399
user6169399

Reputation:

You need to Unmarshal it:

var data *rsa.PrivateKey
err = json.Unmarshal(serverKey, &data)
if err != nil {
    panic(err)
}

And you may use

err = ioutil.WriteFile("secrets.json", buf.Bytes(), 0666)

and

serverKey, err := ioutil.ReadFile("secrets.json")

See:

package main

import (
    "bytes"
    "crypto/rand"
    "crypto/rsa"
    "encoding/json"
    "fmt"
    "io/ioutil"
)

func main() {
    mimicPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
    if err != nil {
        panic(err)
    }
    var buf bytes.Buffer
    err = json.NewEncoder(&buf).Encode(mimicPrivateKey)
    if err != nil {
        panic(err)
    }
    err = ioutil.WriteFile("secrets.json", buf.Bytes(), 0666)
    if err != nil {
        panic(err)
    }

    serverKey, err := ioutil.ReadFile("secrets.json")
    if err != nil {
        panic(err)
    }
    var data *rsa.PrivateKey
    err = json.Unmarshal(serverKey, &data)
    if err != nil {
        panic(err)
    }
    serverKeyPublic := data.PublicKey
    fmt.Println(serverKeyPublic)
}

Upvotes: 2

Related Questions