golang rsa 加密算法

发布时间:2024-12-22 23:12:52

在信息安全领域中,加密技术起到了至关重要的作用。而RSA加密算法作为一种非常经典和常用的公钥加密算法,不仅应用广泛,而且安全性也得到广泛认可。本文将介绍如何使用Golang编写RSA加密算法。

生成RSA密钥对

在使用RSA算法进行加密和解密之前,首先需要生成一对RSA密钥,包括公钥和私钥。这里我们使用Golang内置的crypto/rsa库来实现这项任务。具体可以参考以下代码:

package main

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

func generateRSAKeyPair(bits int) (*rsa.PrivateKey, error) {
	privateKey, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return nil, err
	}

	publicKey := &privateKey.PublicKey

	privateKeyBytes := x509.MarshalPKCS1PrivateKey(privateKey)
	privateKeyPEM := pem.EncodeToMemory(&pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: privateKeyBytes,
	})
	err = os.WriteFile("private.pem", privateKeyPEM, 0644)
	if err != nil {
		return nil, err
	}

	publicKeyBytes, err := x509.MarshalPKIXPublicKey(publicKey)
	if err != nil {
		return nil, err
	}
	publicKeyPEM := pem.EncodeToMemory(&pem.Block{
		Type:  "RSA PUBLIC KEY",
		Bytes: publicKeyBytes,
	})
	err = os.WriteFile("public.pem", publicKeyPEM, 0644)
	if err != nil {
		return nil, err
	}

	return privateKey, nil
}

func main() {
	privateKey, err := generateRSAKeyPair(2048)
	if err != nil {
		fmt.Println("Failed to generate RSA key pair:", err)
		return
	}

	fmt.Println("RSA key pair generated successfully!")
	fmt.Println("Private Key saved as private.pem")
	fmt.Println("Public Key saved as public.pem")
	fmt.Println(privateKey)
}

使用RSA加密数据

当我们已经生成了RSA密钥对之后,可以使用私钥进行加密操作。以下代码展示了如何使用Golang的crypto/rsa库进行数据加密:

package main

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

func encryptData(data []byte, publicKey *rsa.PublicKey) ([]byte, error) {
	ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, data)
	if err != nil {
		return nil, err
	}
	return ciphertext, nil
}

func main() {
	publicKeyPEM, err := ioutil.ReadFile("public.pem")
	if err != nil {
		fmt.Println("Failed to read public key:", err)
		return
	}

	block, _ := pem.Decode(publicKeyPEM)
	publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		fmt.Println("Failed to parse public key:", err)
		return
	}

	publicKey := publicKeyInterface.(*rsa.PublicKey)

	data := []byte("Hello, RSA!")

	ciphertext, err := encryptData(data, publicKey)
	if err != nil {
		fmt.Println("Failed to encrypt data:", err)
		return
	}

	fmt.Println("Data encrypted successfully!")
	fmt.Printf("Ciphertext: %x\n", ciphertext)
}

使用RSA解密数据

在对数据加密后,我们可以使用对应的私钥进行解密操作。下面的代码演示了如何使用Golang的crypto/rsa库进行数据解密:

package main

import (
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"io/ioutil"
	"os"
)

func decryptData(ciphertext []byte, privateKey *rsa.PrivateKey) ([]byte, error) {
	data, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, ciphertext)
	if err != nil {
		return nil, err
	}
	return data, nil
}

func main() {
	privateKeyPEM, err := ioutil.ReadFile("private.pem")
	if err != nil {
		fmt.Println("Failed to read private key:", err)
		return
	}

	block, _ := pem.Decode(privateKeyPEM)
	privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		fmt.Println("Failed to parse private key:", err)
		return
	}

	ciphertext := []byte{0xde, 0xad, 0xbe, 0xef}
	plaintext, err := decryptData(ciphertext, privateKey)
	if err != nil {
		fmt.Println("Failed to decrypt data:", err)
		return
	}

	fmt.Println("Data decrypted successfully!")
	fmt.Printf("Plaintext: %s\n", plaintext)
}

通过以上代码示例,我们可以清晰地了解如何使用Golang的crypto/rsa库来实现RSA加密算法。在实际应用中,我们需要注意保护好私钥的安全,并且保证公钥的正确传输。

相关推荐