Created
May 19, 2023 07:51
-
-
Save parsibox/897e9f43b4dfe762b278406af2c779ec to your computer and use it in GitHub Desktop.
Create private_key and public_key size 2048 with golang for use in JWT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/rand" | |
"crypto/rsa" | |
"crypto/x509" | |
"encoding/pem" | |
"fmt" | |
"io/ioutil" | |
) | |
func main() { | |
// Generate RSA private/public key pair | |
privateKey, err := rsa.GenerateKey(rand.Reader, 2048) | |
if err != nil { | |
panic(err) | |
} | |
publicKey := &privateKey.PublicKey | |
// Encode private key to PEM format and save to file | |
privateKeyBytes := x509.MarshalPKCS1PrivateKey(privateKey) | |
privateKeyPEM := pem.EncodeToMemory(&pem.Block{ | |
Type: "RSA PRIVATE KEY", | |
Bytes: privateKeyBytes, | |
}) | |
err = ioutil.WriteFile("MYKEY/private_key.pem", privateKeyPEM, 0600) | |
if err != nil { | |
panic(err) | |
} | |
// Encode public key to PEM format and save to file | |
publicKeyBytes, err := x509.MarshalPKIXPublicKey(publicKey) | |
if err != nil { | |
panic(err) | |
} | |
publicKeyPEM := pem.EncodeToMemory(&pem.Block{ | |
Type: "PUBLIC KEY", | |
Bytes: publicKeyBytes, | |
}) | |
err = ioutil.WriteFile("MYKEY/public_key.pem", publicKeyPEM, 0644) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("RSA private/public key pair generated and saved to MYKEY folder") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment