Home > Backend Development > Golang > How to Generate RSA Key Pairs in Go: A Comparison with OpenSSL?

How to Generate RSA Key Pairs in Go: A Comparison with OpenSSL?

DDD
Release: 2024-12-10 06:50:14
Original
239 people have browsed it

How to Generate RSA Key Pairs in Go: A Comparison with OpenSSL?

Generating RSA Keys Using Go and Openssl Equivalents

Understanding the Openssl Command

The provided OpenSSL command generates an RSA key pair and saves the private and public keys to separate files. It takes two arguments:

  • $1: Name of the key file (e.g., "key.rsa")
  • $2: Size of the RSA key in bits (e.g., 4096)

Implementing in Go

To replicate this functionality in Go, we need to perform the following steps:

  1. Generate an RSA key pair
  2. Extract the public key component
  3. Convert keys to PKCS#1 ASN.1 DER format
  4. Encode into PEM blocks
  5. Write the keys to files

Go Code:

package main

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

func main() {
    // Define filename and bit size
    filename := "key"
    bitSize := 4096

    // Generate RSA key
    key, err := rsa.GenerateKey(rand.Reader, bitSize)
    if err != nil {
        panic(err)
    }

    // Extract public key
    pub := key.Public()

    // Convert to PKCS#1 DER format
    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)),
        },
    )

    // Write keys to files
    err = ioutil.WriteFile(filename+".rsa", keyPEM, 0700)
    if err != nil {
        panic(err)
    }

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

    fmt.Println("RSA key pair generated and written to files.")
}
Copy after login

Output:

The program will create two files with the following contents:

key.rsa:

-----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----
Copy after login

key.rsa.pub:

-----BEGIN RSA PUBLIC KEY-----
...
-----END RSA PUBLIC KEY-----
Copy after login

The above is the detailed content of How to Generate RSA Key Pairs in Go: A Comparison with OpenSSL?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template