Reputation: 25
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 ?
Upvotes: 1
Views: 2446
Reputation: 2036
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() )
Upvotes: 1