-1

I have generated a RSA private key (using crypto/rsa) and corresponding public key in go. Now I want to write them to two files (each one to a file), but WriteString and Write functions are specific to string and []byte variable. Also instructions like String(privateKey) generate error. How I can write these keys to the files?

sh.sagheb
  • 27
  • 1
  • 1
  • 7
  • 2
    https://stackoverflow.com/questions/13555085/save-and-load-crypto-rsa-privatekey-to-and-from-the-disk https://stackoverflow.com/questions/64104586/use-golang-to-get-rsa-key-the-same-way-openssl-genrsa – dave_thompson_085 Oct 29 '22 at 06:55

1 Answers1

1

You would need pem.Encode. An example can be seen in maplepie/rsa#savePrivateKey():

func (p *PemKey) savePrivateKey(privateKey *rsa.PrivateKey, filename string) error {
    raw := x509.MarshalPKCS1PrivateKey(privateKey)
    block := &pem.Block{
        Type:  "RSA PRIVATE KEY",
        Bytes: raw,
    }
    file, err := os.Create(filename)
    if err != nil {
        return err
    }
    err = pem.Encode(file, block)
    if err != nil {
        return err
    }
    return nil
}

Same idea for public key:

func (p *PemKey) savePublicKey(publicKey *rsa.PublicKey, filename string) error {
    raw, err := x509.MarshalPKIXPublicKey(publicKey)
    if err != nil {
        return err
    }
    block := &pem.Block{
        Type:  "PUBLIC KEY",
        Bytes: raw,
    }
    file, err := os.Create(filename)
    if err != nil {
        return err
    }
    err = pem.Encode(file, block)
    if err != nil {
        return err
    }
    return nil
}
blackgreen
  • 34,072
  • 23
  • 111
  • 129
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250