golang+rsa算法

发布时间:2024-07-05 01:06:25

OpenSSL是一款功能强大的加密开源软件库,支持多种密码算法,其中RSA是非对称加密算法的一种。在Golang中,我们也可以使用RSA算法实现数据的加密和解密。本文将介绍Golang中使用RSA算法的方法。

生成RSA密钥对

RSA算法需要一个密钥对,包括公钥和私钥。公钥用于加密数据,私钥用于解密数据。我们可以使用Golang中的crypto/rsa包来生成RSA密钥对。

首先,我们需要指定RSA密钥长度,一般建议使用2048位。代码如下:

package main

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

func main() {
    // 指定RSA密钥长度为2048位
    privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)

    // 将私钥保存到文件中
    privateKeyFile, _ := os.Create("private.pem")
    defer privateKeyFile.Close()
    privateKeyPEM := &pem.Block{
        Type:  "RSA PRIVATE KEY",
        Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
    }
    pem.Encode(privateKeyFile, privateKeyPEM)

    // 提取公钥
    publicKey := privateKey.PublicKey

    // 将公钥保存到文件中
    publicKeyFile, _ := os.Create("public.pem")
    defer publicKeyFile.Close()
    publicKeyPEM := &pem.Block{
        Type:  "RSA PUBLIC KEY",
        Bytes: x509.MarshalPKCS1PublicKey(&publicKey),
    }
    pem.Encode(publicKeyFile, publicKeyPEM)
}

上述代码将生成私钥文件private.pem和公钥文件public.pem。我们可以使用openssl命令来查看生成的密钥对:

openssl rsa -in private.pem -text
openssl rsa -pubin -in public.pem -text

数据加密

有了RSA密钥对,我们就可以使用公钥对数据进行加密。Golang中的crypto/rsa包提供了EncryptPKCS1v15函数来实现加密。

package main

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

func main() {
    // 读取公钥
    publicKeyFile, _ := os.Open("public.pem")
    defer publicKeyFile.Close()
    publicKeyBytes, _ := ioutil.ReadAll(publicKeyFile)
    publicKeyPEM, _ := pem.Decode(publicKeyBytes)
    publicKey, _ := x509.ParsePKCS1PublicKey(publicKeyPEM.Bytes)

    // 原始数据
    plaintext := []byte("Hello, RSA encryption!")

    // 使用公钥加密数据
    ciphertext, _ := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plaintext)

    fmt.Printf("Cipher text: %x\n", ciphertext)
}

上述代码将使用公钥对原始数据进行加密,并打印出加密后的密文。

数据解密

在接收到加密数据后,我们可以使用私钥对其进行解密。Golang中的crypto/rsa包提供了DecryptPKCS1v15函数来实现解密。

package main

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

func main() {
    // 读取私钥
    privateKeyFile, _ := os.Open("private.pem")
    defer privateKeyFile.Close()
    privateKeyBytes, _ := ioutil.ReadAll(privateKeyFile)
    privateKeyPEM, _ := pem.Decode(privateKeyBytes)
    privateKey, _ := x509.ParsePKCS1PrivateKey(privateKeyPEM.Bytes)

    // 密文数据
    ciphertext := []byte{...} // 加密后的密文

    // 使用私钥解密数据
    plaintext, _ := rsa.DecryptPKCS1v15(rand.Reader, privateKey, ciphertext)

    fmt.Printf("Plain text: %s\n", plaintext)
}

上述代码将使用私钥对密文进行解密,并打印出解密后的明文。

相关推荐