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

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

Susan Sarandon
Release: 2024-12-14 15:49:14
Original
841 people have browsed it

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

Use Go to Generate RSA Keys in the Same Way as Openssl

The OpenSSL command openssl genrsa generates a pair of RSA keys, storing the private key in one file and the public key in another. To achieve this functionality in Go, you can follow these steps:

  1. Generate the RSA key pair:
import "crypto/rand"

key, err := rsa.GenerateKey(rand.Reader, bitSize)
if err != nil {
    panic(err)
}
Copy after login
  1. Extract the public key:
import "crypto/rsa"

pub := key.Public()
Copy after login
  1. Encode the keys in PEM format:
import (
    "encoding/pem"
    "crypto/x509"
)

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)),
    },
)
Copy after login
  1. Write the PEM-encoded keys to files:
import "io/ioutil"

err := ioutil.WriteFile(filename+".rsa", keyPEM, 0700)
err := ioutil.WriteFile(filename+".rsa.pub", pubPEM, 0755)
Copy after login

This code will generate two files, filename.rsa and filename.rsa.pub, containing the private and public RSA keys respectively. The keys will be in the PEM format, which allows you to easily import and use them with other applications.

The above is the detailed content of How Can I Generate RSA Key Pairs in Go, Similar to OpenSSL's `openssl 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