我想生成 ssh key ,公钥和私钥,并以字符串形式返回,但我不知道如何将类型 *pem.Block 转换为字符串。
这是我当前的代码:
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/asn1"
"encoding/pem"
"fmt"
"bytes"
"bufio"
)
func Keymaker() {
reader := rand.Reader
bitSize := 2048
key, err := rsa.GenerateKey(reader, bitSize)
if err != nil {
//return nil, nil, err
}
publicKey := key.PublicKey
var privateKey = &pem.Block{
Type: "PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
}
asn1Bytes, err := asn1.Marshal(publicKey)
if err != nil {
//return nil, nil, err
}
var pemkey = &pem.Block{
Type: "PUBLIC KEY",
Bytes: asn1Bytes,
}
var PublicKeyRow bytes.Buffer
err = pem.Encode(bufio.NewWriter(&PublicKeyRow), pemkey)
fmt.Println("public_key : ", PublicKeyRow)
fmt.Println("private_key : ", privateKey )
return
}
func main() {
Keymaker()
}
这是我当前的错误:
# command-line-arguments
./dkim.go:46:38: cannot convert privateKey (type *pem.Block) to type string
我需要字符串格式,因为我想将 key 存储在数据库中,如何将(类型 *pem.Block)转换为字符串类型?以及如何将(类型 bytes.Buffer)转换为类型字符串?
最佳答案
您的 PublicKeyRow
已经是您要写入的正确 io.Writer
。您不需要通过 buffio.NewWriter(&PublicKeyRow)
创建另一个。因此,要将 pem.Block
转换为字符串,您的最后几行应如下所示:
var PublicKeyRow bytes.Buffer
err = pem.Encode(&PublicKeyRow, pemkey)
fmt.Println("public_key : ", PublicKeyRow)
fmt.Println("public_key(string) : ", PublicKeyRow.String())
fmt.Println("private_key : ", privateKey )
更新 要获得私钥,您可以添加另一个编码
var PublicKeyRow bytes.Buffer
var PrivateKeyRow bytes.Buffer
err = pem.Encode(&PublicKeyRow, pemkey)
err = pem.Encode(&PrivateKeyRow, privateKey)
fmt.Println("public_key: ", PublicKeyRow.String())
fmt.Println("private_key : ", PrivateKeyRow.String() )
关于go - 无法将 privateKey 类型 pem.Block 转换为类型字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54615970/