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.
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.
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
The inverse function is http://golang.org/pkg/crypto/x509/#ParsePKCS1PrivateKey.
However, it is relatively standard to encode the marshaled key into a PEM file.
You can find a full example here.
Since the public key part of your question wasn't answered and I just ran into the same problem and solved it, here it is:
Note the
&
in front of the Argument toMarshalPKIXPublicKey
Relevant reads:
PS: MarshalPKIXPublicKey also accepts ECDSA keys, ajust the pem header appropriately.
Here's code snippet that shows the import and export of both public and private keys. It's based on the other answers which were super helpful, as well as copy-pasta from the official docs.