Home >Backend Development >Golang >How Can I Encrypt and Decrypt RSA Keys in Go?

How Can I Encrypt and Decrypt RSA Keys in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-05 01:42:10625browse

How Can I Encrypt and Decrypt RSA Keys in Go?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn