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

标签 go

我想生成 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/

相关文章:

json - 使用 json.Decoder 解码顶级 JSON 数组

go - Golang 中的持久化调度

session - cookie 和 cookiejar 有什么区别?

json - golang : Unmarshal: json: cannot unmarshal array into Go value of type main. MonitorServerInfo

go - Go 中使用 channel 的斐波那契数列

python - 使用 Go/Python 使用 CSRF token 登录站点

Golang JSON 标签

go - Go中字符串的顺序输出和输入

windows - 从 Go 程序调用 Windows 批处理文件,以便它在新窗口中打开

go - 如何将一个字符与同一字符串中的下一个字符进行比较