Home > Backend Development > Golang > How Can I Generate RSA Key Pairs in Go, Mimicking OpenSSL's `genrsa` Command?

How Can I Generate RSA Key Pairs in Go, Mimicking OpenSSL's `genrsa` Command?

Barbara Streisand
Release: 2024-12-15 22:08:16
Original
759 people have browsed it

How Can I Generate RSA Key Pairs in Go, Mimicking OpenSSL's `genrsa` Command?

Generating RSA Keys with Go: Replicating Openssl genrsa

The OpenSSL command openssl genrsa -out $1.rsa $2 generates an RSA key pair and exports them to two separate files, $1.rsa for the private key and $1.rsa.pub for the public key. In Go, this process involves:

  • Generating an RSA key pair
  • Extracting the public key
  • Converting the keys to PKCS#1 ASN.1 DER format
  • Encoding them into PEM blocks
  • Writing the keys to files

The following code demonstrates this process:

package main

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "encoding/pem"
    "io/ioutil"
)

func main() {
    filename := "key"
    bitSize := 4096

    key, err := rsa.GenerateKey(rand.Reader, bitSize)
    if err != nil {
        panic(err)
    }
    pub := key.Public()
    keyPEM := pem.EncodeToMemory(
        &pem.Block{
            Type:  "RSA PRIVATE KEY",
            Bytes: x509.MarshalPKCS1PrivateKey(key),
        },
    )

    pubPEM := pem.EncodeToMemory(
        &pem.Block{
            Type:  "RSA PUBLIC KEY",
            Bytes: x509.MarshalPKCS1PublicKey(pub.(*rsa.PublicKey)),
        },
    )

    if err := ioutil.WriteFile(filename+".rsa", keyPEM, 0700); err != nil {
        panic(err)
    }

    if err := ioutil.WriteFile(filename+".rsa.pub", pubPEM, 0755); err != nil {
        panic(err)
    }
}
Copy after login

This code generates the private key file key.rsa and the public key file key.rsa.pub. The contents of these files resemble the output of the OpenSSL command.

The above is the detailed content of How Can I Generate RSA Key Pairs in Go, Mimicking OpenSSL's `genrsa` Command?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template