Home >Backend Development >Golang >How to Generate RSA Key Pairs in Go and Write Them to Separate Files?

How to Generate RSA Key Pairs in Go and Write Them to Separate Files?

Barbara Streisand
Barbara StreisandOriginal
2024-12-16 13:35:10459browse

How to Generate RSA Key Pairs in Go and Write Them to Separate Files?

Generating RSA Keys in Go Like openssl genrsa

Overview

The openssl command genrsa generates RSA keys. We can achieve the same functionality in Go using the crypto/rsa package. This article provides a detailed walkthrough of how to generate RSA key pairs and write them to separate files in Go.

Step-by-Step Guide

1. Import Necessary Libraries

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

2. Generate Key Pair

filename := "key"
bitSize := 4096

// Generate RSA keypair
key, err := rsa.GenerateKey(rand.Reader, bitSize)

3. Extract Public Component

pub := key.Public()

4. Encode to PEM

// Encode private key to PKCS#1 ASN.1 PEM
keyPEM := pem.EncodeToMemory(
    &pem.Block{
        Type:  "RSA PRIVATE KEY",
        Bytes: x509.MarshalPKCS1PrivateKey(key),
    },
)

// Encode public key to PKCS#1 ASN.1 PEM
pubPEM := pem.EncodeToMemory(
    &pem.Block{
        Type:  "RSA PUBLIC KEY",
        Bytes: x509.MarshalPKCS1PublicKey(pub.(*rsa.PublicKey)),
    },
)

5. Write to Files

// Write private key to file
if err := ioutil.WriteFile(filename+".rsa", keyPEM, 0700); err != nil {
    panic(err)
}

// Write public key to file
if err := ioutil.WriteFile(filename+".rsa.pub", pubPEM, 0755); err != nil {
    panic(err)
}

Conclusion

By following the steps outlined above, you can effortlessly generate RSA key pairs and write them to separate files in Go, similar to the openssl genrsa command. This comprehensive guide provides a solid foundation for working with RSA keys in your Go applications.

The above is the detailed content of How to Generate RSA Key Pairs in Go and Write Them to Separate Files?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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