Encrypting and Decrypting RSA Keys
The Go programming language provides the crypto/rsa package for handling RSA keys. However, it may not be immediately evident how to effectively save and load these keys for later use.
Encoding Private RSA Keys
To convert an rsa.PrivateKey to a []byte, the crypto/x509 package offers a specific function:
func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte
This function marshals the private key into a byte array. To recover the key from the bytes, use:
func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err error)
Marshaling the Key in PEM Format
A common practice is to encode the marshaled key into a PEM file. The following code sample demonstrates this:
pemdata := pem.EncodeToMemory( &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key), }, )
The above is the detailed content of How Can I Encrypt and Decrypt RSA Keys in Go?. For more information, please follow other related articles on the PHP Chinese website!