我想生成ssh密钥(公共和私有)并以字符串形式返回,但我不知道如何转换类型* pem.Block in string。
这是我当前的代码:
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
我需要字符串格式,因为我想将密钥存储在数据库中,如何将(* pem.Block类型)转换为字符串类型?以及如何将(类型为bytes.Buffer)转换为字符串?
答案 0 :(得分:0)
您的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() )