Save and load crypto/rsa PrivateKey to and from the disk

Alexander Bauer picture Alexander Bauer · Nov 25, 2012 · Viewed 36.1k times · Source

I'm using crypto/rsa, and trying to find a way to properly save and load a key. Is there a correct way to create a []byte from an rsa.PrivateKey. If so, is there a way to properly do so for an rsa.PublicKey?

Thank you all very much.

Answer

Stephen Weinberg picture Stephen Weinberg · Nov 25, 2012

You need some sort of format to marshal the key into. One format supported by the Go standard library can be found here: http://golang.org/pkg/crypto/x509/#MarshalPKCS1PrivateKey

func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte

The inverse function is http://golang.org/pkg/crypto/x509/#ParsePKCS1PrivateKey.

func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err error)

However, it is relatively standard to encode the marshaled key into a PEM file.

pemdata := pem.EncodeToMemory(
    &pem.Block{
        Type: "RSA PRIVATE KEY",
        Bytes: x509.MarshalPKCS1PrivateKey(key),
    },
)

You can find a full example here.