Go语言通过crypto包实现AES和RSA加密解密:1. AES使用CBC模式和PKCS7填充,需密钥和IV,适合大量数据加密;2. RSA为非对称加密,公钥加密私钥解密,常用于密钥交换;3. 实际应用推荐AES加密数据、RSA加密AES密钥的混合加密方案,注意密钥安全与填充模式选择。

Go语言的
crypto
包提供了强大的加密支持,常用于数据安全传输。其中AES(对称加密)和RSA(非对称加密)是使用最广泛的两种算法。下面介绍如何在Go中实现AES和RSA的加密解密功能。
AES 加密解密(CBC模式)
AES是一种对称加密算法,加密和解密使用相同的密钥,适合加密大量数据。
说明: 使用AES-CBC模式,需要密钥(16/24/32字节)和初始化向量IV(16字节),并进行PKCS7填充。
示例代码:
立即学习“go语言免费学习笔记(深入)”;
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)%blockSizepadtext := 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) 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("密文: %sn", encrypted)decrypted, err := aesDecrypt(encrypted, key)if err != nil { panic(err)}fmt.Printf("明文: %sn", decrypted)
}
RSA 加密解密(公钥私钥)
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("密文: %sn", encrypted)decrypted, err := rsaDecrypt(encrypted, "private.pem")if err != nil { panic(err)}fmt.Printf("明文: %sn", decrypted)
}
使用建议
实际应用中,通常结合使用AES和RSA:
用AES加密数据(速度快)用RSA加密AES密钥(安全传输)即“混合加密”系统
注意密钥管理、填充模式选择(如OAEP更安全)、避免硬编码密钥等安全问题。
基本上就这些。Go的crypto库设计清晰,只要理解加密原理,实现起来并不复杂但容易忽略细节。
以上就是Golang的crypto加密解密 AES/RSA实现的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1400571.html
微信扫一扫
支付宝扫一扫