Go生成RSA密钥对


golang 原生库生成RSA密钥对,公钥和私钥保存为文件

package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"os"
)

func generateRSAKey(privateFile, publicFile string, bits int) error {
	// 生成 RSA 私钥对象
	privateKey, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return err
	}

	// 通过x509标准将得到的ras私钥序列化为 ASN.1 的 DER 编码字符串
	x509PrivateKey := x509.MarshalPKCS1PrivateKey(privateKey)

	// 新建私钥文件
	private, err := os.Create(privateFile)
	if err != nil {
		return err
	}
	defer private.Close()

	// 将数据保存到文件
	err = pem.Encode(private, &pem.Block{
		Type:    "RSA Private Key",
		Headers: map[string]string{},
		Bytes:   x509PrivateKey,
	})
	if err != nil {
		return err
	}

	// X509对公钥编码
	X509PublicKey, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
	if err != nil {
		return err
	}

	// 新建公钥文件
	public, err := os.Create(publicFile)
	if err != nil {
		return err
	}
	defer public.Close()

	// 将数据保存到文件
	err = pem.Encode(public, &pem.Block{
		Type:    "RSA Public Key",
		Headers: map[string]string{},
		Bytes:   X509PublicKey,
	})
	if err != nil {
		return err
	}

	return nil
}

func main() {
	generateRSAKey("./private.key", "./public.key", 4096)
}