dongtao5055 2019-02-10 11:38
浏览 262
已采纳

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

i want to generate ssh key, public and private and return as string, but i dont know how i can convert type *pem.Block in string.

this is my current code :

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()

}

and this is my current error:

# command-line-arguments
./dkim.go:46:38: cannot convert privateKey (type *pem.Block) to type string

I need in string format because i want to store the key in database, how i can convert (type *pem.Block) to type string ? and how i can convert (type bytes.Buffer) to type string ?

  • 写回答

1条回答 默认 最新

  • douwayuan3063 2019-02-10 12:21
    关注

    Your PublicKeyRow is already correct io.Writer that you want to write to. You do not need to create another by buffio.NewWriter(&PublicKeyRow). So to convert pem.Block to string your last lines should look like this:

    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 )
    

    Update To get private key you could add another encode

    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() )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog