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
Release: 2024-12-16 13:35:10
Original
418 people have browsed it

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"
)
Copy after login

2. Generate Key Pair

filename := "key"
bitSize := 4096

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

3. Extract Public Component

pub := key.Public()
Copy after login

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)),
    },
)
Copy after login

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)
}
Copy after login

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!

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