### Golang 中 RSA 公私钥生成与使用
在 Go 语言中,可以利用 `crypto/rsa` 和其他相关包来生成和操作 RSA 密钥对。下面是一个完整的例子展示如何创建并保存这些密钥。
#### 创建 RSA 密钥对
为了生成一对新的 RSA 私钥和相应的公钥,可采用如下方式:
```go
package main
import (
"crypto/rand"
"crypto/rsa"
"fmt"
"log"
)
func generateRSAKeyPair(bits int) (*rsa.PrivateKey, *rsa.PublicKey, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return nil, nil, fmt.Errorf("error generating key: %v", err)
}
publicKey := &privateKey.PublicKey
return privateKey, publicKey, nil
}
func main() {
privateKey, publicKey, err := generateRSAKeyPair(2048)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Private Key:\n%+v\n", privateKey)
fmt.Printf("Public Key:\n%+v\n", publicKey)
}
```
这段代码定义了一个名为 `generateRSAKeyPair` 的函数用于生成指定长度位数的 RSA 密钥对[^1]。
#### 将密钥编码为 PEM 格式
通常情况下,人们更倾向于以 `.pem` 文件的形式存储密钥数据。这可以通过调用标准库中的 `encoding/pem` 来完成:
```go
package main
import (
"crypto/rand"
"crypto/rsa"
"encoding/pem"
"fmt"
"io/ioutil"
"log"
)
// savePrivateKeyToPEMFile saves the given private key into a .pem file.
func savePrivateKeyToPEMFile(filename string, privateKey *rsa.PrivateKey) error {
privateBytes := pem.EncodeToMemory(
&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
},
)
err := ioutil.WriteFile(filename, privateBytes, 0600)
return err
}
// savePublicKeyToPEMFile saves the public part of an RSA key pair to a .pem file.
func savePublicKeyToPEMFile(filename string, publicKey *rsa.PublicKey) error {
publicASN1, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
return err
}
publicBytes := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: publicASN1})
err = ioutil.WriteFile(filename, publicBytes, 0644)
return err
}
func main() {
privateKey, publicKey, err := generateRSAKeyPair(2048)
if err != nil {
log.Fatal(err)
}
err = savePrivateKeyToPEMFile("private.pem", privateKey)
if err != nil {
log.Fatal(err)
}
err = savePublicKeyToPEMFile("public.pem", publicKey)
if err != nil {
log.Fatal(err)
}
fmt.Println("Keys have been saved successfully.")
}
```
此部分展示了怎样把之前产生的密钥转换成适合长期储存的人类可读形式——即 PEM 编码格式,并将其写入磁盘上的两个独立文件中[^3]。