您的位置:首页 >Golang AES/RSA加密解密实现方法
发布于2025-12-31 阅读(0)
扫一扫,手机访问
Go语言通过crypto包实现AES和RSA加密解密:1. AES使用CBC模式和PKCS7填充,需密钥和IV,适合大量数据加密;2. RSA为非对称加密,公钥加密私钥解密,常用于密钥交换;3. 实际应用推荐AES加密数据、RSA加密AES密钥的混合加密方案,注意密钥安全与填充模式选择。

Go语言的crypto包提供了强大的加密支持,常用于数据安全传输。其中AES(对称加密)和RSA(非对称加密)是使用最广泛的两种算法。下面介绍如何在Go中实现AES和RSA的加密解密功能。
AES是一种对称加密算法,加密和解密使用相同的密钥,适合加密大量数据。
说明: 使用AES-CBC模式,需要密钥(16/24/32字节)和初始化向量IV(16字节),并进行PKCS7填充。
示例代码:
package mainimport ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "fmt" "io" )
// AES加密(PKCS7填充) func aesEncrypt(plaintext []byte, key []byte) (string, error) { block, err := aes.NewCipher(key) if err != nil { return "", err }
// 使用PKCS7填充 blockSize := block.BlockSize() padding := blockSize - len(plaintext)%blockSize padtext := append(plaintext, bytes.Repeat([]byte{byte(padding)}, padding)...) ciphertext := make([]byte, aes.BlockSize+len(padtext)) iv := ciphertext[:aes.BlockSize] if _, err := io.ReadFull(rand.Reader, iv); err != nil { return "", err } mode := cipher.NewCBCEncrypter(block, iv) mode.CryptBlocks(ciphertext[aes.BlockSize:], padtext) return base64.StdEncoding.EncodeToString(ciphertext), nil}
// AES解密 func aesDecrypt(ciphertext string, key []byte) ([]byte, error) { data, err := base64.StdEncoding.DecodeString(ciphertext) if err != nil { return nil, err }
block, err := aes.NewCipher(key) if err != nil { return nil, err } if len(data) < aes.BlockSize { return nil, fmt.Errorf("密文太短") } iv := data[:aes.BlockSize] data = data[aes.BlockSize:] if len(data)%aes.BlockSize != 0 { return nil, fmt.Errorf("密文长度不是块大小的整数倍") } mode := cipher.NewCBCDecrypter(block, iv) mode.CryptBlocks(data, data) // 去除PKCS7填充 padding := int(data[len(data)-1]) if padding > len(data) { return nil, fmt.Errorf("无效填充") } return data[:len(data)-padding], nil}
func main() { key := []byte("1234567890123456") // 16字节密钥(AES-128) plaintext := []byte("Hello, AES!")
encrypted, err := aesEncrypt(plaintext, key) if err != nil { panic(err) } fmt.Printf("密文: %s\n", encrypted) decrypted, err := aesDecrypt(encrypted, key) if err != nil { panic(err) } fmt.Printf("明文: %s\n", decrypted)}
RSA是非对称加密算法,使用公钥加密,私钥解密,适合密钥交换或小数据加密。
说明: Go中使用crypto/rsa和crypto/rand,通常结合PKCS1v15或OAEP填充。
生成密钥对:
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"os"
)
// 生成RSA密钥对(2048位)
func generateRSAKeys() error {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return err
}
// 保存私钥
privFile, err := os.Create("private.pem")
if err != nil {
return err
}
defer privFile.Close()
privBytes := x509.MarshalPKCS1PrivateKey(privateKey)
privBlock := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: privBytes,
}
pem.Encode(privFile, privBlock)
// 保存公钥
pubFile, err := os.Create("public.pem")
if err != nil {
return err
}
defer pubFile.Close()
pubBytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
if err != nil {
return err
}
pubBlock := &pem.Block{
Type: "PUBLIC KEY",
Bytes: pubBytes,
}
pem.Encode(pubFile, pubBlock)
return nil
}
RSA加密与解密:
// RSA公钥加密
func rsaEncrypt(plaintext []byte, pubFile string) (string, error) {
file, err := os.Open(pubFile)
if err != nil {
return "", err
}
defer file.Close()
info, _ := file.Stat()
buf := make([]byte, info.Size())
file.Read(buf)
block, _ := pem.Decode(buf)
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return "", err
}
pubKey := pubInterface.(*rsa.PublicKey)
ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey, plaintext)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
// RSA私钥解密
func rsaDecrypt(ciphertext string, privFile string) ([]byte, error) {
data, err := base64.StdEncoding.DecodeString(ciphertext)
if err != nil {
return nil, err
}
file, err := os.Open(privFile)
if err != nil {
return nil, err
}
defer file.Close()
info, _ := file.Stat()
buf := make([]byte, info.Size())
file.Read(buf)
block, _ := pem.Decode(buf)
privKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
plaintext, err := rsa.DecryptPKCS1v15(rand.Reader, privKey, data)
if err != nil {
return nil, err
}
return plaintext, nil}
func main() {
// 生成密钥
generateRSAKeys()
plaintext := []byte("Hello, RSA!")
encrypted, err := rsaEncrypt(plaintext, "public.pem")
if err != nil {
panic(err)
}
fmt.Printf("密文: %s\n", encrypted)
decrypted, err := rsaDecrypt(encrypted, "private.pem")
if err != nil {
panic(err)
}
fmt.Printf("明文: %s\n", decrypted)}
实际应用中,通常结合使用AES和RSA:
注意密钥管理、填充模式选择(如OAEP更安全)、避免硬编码密钥等安全问题。
基本上就这些。Go的crypto库设计清晰,只要理解加密原理,实现起来并不复杂但容易忽略细节。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9