Search code examples
gocryptographyrsaprivate-keypublic-key

How to write *PrivateKey type variable to a file in golang?


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?


Solution

  • 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
    }