为了账号安全,请及时绑定邮箱和手机立即绑定

无法将 privateKey 类型 pem.Block 转换为类型字符串

无法将 privateKey 类型 pem.Block 转换为类型字符串

Go
江户川乱折腾 2023-06-05 18:18:37
我想生成 ssh 密钥,公钥和私钥,并以字符串形式返回,但我不知道如何将类型 *pem.Block 转换为字符串。这是我当前的代码:package mainimport (    "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我需要字符串格式,因为我想将密钥存储在数据库中,如何将 (type *pem.Block) 转换为 string 类型?以及如何将(类型 bytes.Buffer)转换为类型字符串?
查看完整描述

1 回答

?
慕桂英4014372

TA贡献1871条经验 获得超13个赞

您想要写信给PublicKeyRow已经是正确的。io.Writer您不需要创建另一个 by 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() )


查看完整回答
反对 回复 2023-06-05
  • 1 回答
  • 0 关注
  • 113 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信