Golang RSA加密解密实战

最近在学习Golang的RSA加密解密,遇到几个问题想请教大家:

  1. 如何正确生成RSA公私钥对?我用GenerateKey生成的密钥在解密时总是报错
  2. 加密时数据长度有限制吗?大文件要怎么分段处理?
  3. 用OAEP填充模式时,加密后的数据比原数据长很多,这正常吗?
  4. 有没有完整的示例代码可以参考?官方文档看得不是很明白 求有经验的大佬指点迷津!
2 回复

在Go中使用RSA加密解密,主要依赖crypto/rsacrypto/rand包。以下是核心步骤:

1. 生成密钥对

privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
publicKey := &privateKey.PublicKey

2. 加密(使用公钥)

ciphertext, _ := rsa.EncryptOAEP(
    sha256.New(),
    rand.Reader,
    publicKey,
    []byte("秘密消息"),
    nil,
)

3. 解密(使用私钥)

plaintext, _ := rsa.DecryptOAEP(
    sha256.New(),
    rand.Reader,
    privateKey,
    ciphertext,
    nil,
)

关键点:

  • 推荐使用OAEP填充模式(更安全)
  • 2048位是当前安全的最小长度
  • 加密内容长度受限(例如2048位密钥最多加密190字节)
  • 处理大文件时应使用对称加密+ RSA加密密钥

注意: 实际使用务必处理所有错误,以上代码省略了错误处理。

更多关于Golang RSA加密解密实战的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Golang中,使用RSA进行加密解密通常涉及生成密钥对、加密数据和解密数据。以下是完整示例:

1. 生成RSA密钥对

package main

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

func generateKeyPair(bits int) (*rsa.PrivateKey, *rsa.PublicKey) {
	privateKey, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		log.Fatal(err)
	}
	return privateKey, &privateKey.PublicKey
}

2. 加密函数

func encrypt(publicKey *rsa.PublicKey, data []byte) ([]byte, error) {
	return rsa.EncryptPKCS1v15(rand.Reader, publicKey, data)
}

3. 解密函数

func decrypt(privateKey *rsa.PrivateKey, ciphertext []byte) ([]byte, error) {
	return rsa.DecryptPKCS1v15(rand.Reader, privateKey, ciphertext)
}

4. 完整示例

func main() {
	// 生成2048位RSA密钥对
	privateKey, publicKey := generateKeyPair(2048)
	
	originalData := []byte("Hello, RSA Encryption!")
	
	// 加密
	encrypted, err := encrypt(publicKey, originalData)
	if err != nil {
		log.Fatal("加密失败:", err)
	}
	fmt.Printf("加密结果: %x\n", encrypted)
	
	// 解密
	decrypted, err := decrypt(privateKey, encrypted)
	if err != nil {
		log.Fatal("解密失败:", err)
	}
	fmt.Printf("解密结果: %s\n", decrypted)
}

重要说明:

  1. RSA加密有长度限制,加密数据长度不能超过密钥长度减去11字节(PKCS1v1.5填充)
  2. 实际应用中通常使用混合加密:用RSA加密对称密钥,再用对称密钥加密数据
  3. 生产环境应使用OAEP填充(更安全):
    func encryptOAEP(publicKey *rsa.PublicKey, data []byte) ([]byte, error) {
        return rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, data, nil)
    }
    

密钥保存示例:

func saveKeyToFile(key *rsa.PrivateKey, filename string) {
	keyBytes := x509.MarshalPKCS1PrivateKey(key)
	pemBlock := &pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: keyBytes,
	}
	// 保存到文件...
}

这个示例展示了基本的RSA加密解密流程,实际使用时请根据安全需求选择合适的填充方式和密钥长度。

回到顶部