How to implement RSA encryption in Golang?

In Golang, you can use the crypto/rsa package to implement RSA encryption. Here is a simple example code:

package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"fmt"
)

func main() {
	// 生成RSA密钥对
	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Println("Failed to generate RSA key pair:", err)
		return
	}

	// 将私钥保存为PEM格式
	privateKeyPem := &pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
	}
	privateKeyPemBytes := pem.EncodeToMemory(privateKeyPem)
	fmt.Println("Private key (PEM format):")
	fmt.Println(string(privateKeyPemBytes))

	// 将公钥保存为PEM格式
	publicKey := &privateKey.PublicKey
	publicKeyDer, err := x509.MarshalPKIXPublicKey(publicKey)
	if err != nil {
		fmt.Println("Failed to convert public key to DER format:", err)
		return
	}
	publicKeyPem := &pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: publicKeyDer,
	}
	publicKeyPemBytes := pem.EncodeToMemory(publicKeyPem)
	fmt.Println("Public key (PEM format):")
	fmt.Println(string(publicKeyPemBytes))

	// 加密数据
	plainText := []byte("Hello, RSA encryption!")
	cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plainText)
	if err != nil {
		fmt.Println("Failed to encrypt data:", err)
		return
	}
	fmt.Println("Cipher text:")
	fmt.Println(cipherText)

	// 解密数据
	decryptedText, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, cipherText)
	if err != nil {
		fmt.Println("Failed to decrypt data:", err)
		return
	}
	fmt.Println("Decrypted text:")
	fmt.Println(string(decryptedText))
}

In the example code above, a 2048-bit RSA key pair is first generated. The private key is then saved in PEM format and printed out. Next, the public key is saved in PEM format and printed out as well.

Next, encrypt the data using the public key and output the encrypted ciphertext. Finally, decrypt the ciphertext using the private key and output the decrypted plaintext.

Please be sure to securely store your private key to prevent it from being leaked in practical applications.

bannerAds