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
Release: 2024-12-05 01:42:10
Original
591 people have browsed it

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
Copy after login

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)
Copy after login

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),
    },
)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template