How to generate a RSA key pair in Windows 10?

Asked

Viewed 373 times

0

I’m trying to use jwt, more specifically the jwt to go, but I need to generate a key pair (a public and a private) RSA, I tried to generate by puttygen but Dã error Key must be PEM encoded PKCS1 or PKCS8 private key. I also tried openssl but it is not recognized by Windows. There is something for Windows 10 to generate RSA?

  • Recently I had a problem with how to generate rsa keys to be valid for validating with jwt. I got the result I wanted. Follow the project link. Heimdall

2 answers

1

JWT supports ECDSA (and I think also Eddsa), which I believe is better than RSA due to its smaller size.

But if you want to generate a key you could use Golang himself, he has the following cryptographic functions:

  • rsa.GenerateKey.
  • x509.MarshalPKCS8PrivateKey
  • pem.EncodeToMemory

That I believe are enough for that.


package main

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

func main() {
    key, err := rsa.GenerateKey(rand.Reader, 4092)
    if err != nil {
        panic("Error")
    }

    pkcs, err := x509.MarshalPKCS8PrivateKey(key)
    if err != nil {
        panic("Error")
    }

    pem := pem.EncodeToMemory(
        &pem.Block{
            Type:  "RSA PRIVATE KEY",
            Bytes: pkcs,
        })

    fmt.Println(string(pem))
}

This needs GO 1.10, or use MarshalPKCS1PrivateKey which is supported in previous versions.

1


Go has a tool for you to generate keys. Open Command Terminal and do the following:

> cd %GOROOT%\src\crypto\tls
> go run generate_cert.go --host localhost --ca true

//Substitua C:\ pelo local onde você quer que os arquivos fiquem
> move %GOROOT%\src\crypto\tls\cert.pem C:\cert.pem
> move %GOROOT%\src\crypto\tls\key.pem C:\key.pem

Now, in your go code, just do the following (I didn’t treat the errors to simplify the example):

//Substitua C:\ para o local onde estão os arquivos, caso você os tenha mudado de lugar
keyPEM, _ := ioutil.ReadFile("C:\key.pem")
privateKey, _ = jwt.ParseRSAPrivateKeyFromPEM(keyPEM)
certPEM, _ := ioutil.ReadFile("C:\cert.pem")
publicKey, _ = jwt.ParseRSAPublicKeyFromPEM(certPEM)

t := jwt.NewWithClaims(jwt.GetSigningMethod("RS256"), jwt.MapClaims{
    //Suas Claims
})

signedToken, err := t.SignedString(signKey)
//Etc...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.