Golangcrypto加密使用详解
时间:2025-11-06
浏览:186
作者:佚名
**Golang crypto包加密使用教程:AES、RSA与SHA-256实战指南** 本文深入解析Golang `crypto`包的加密应用,重点讲解AES对称加密、RSA非对称加密以及SHA-256哈希算法的使用。针对AES加密,我们将演示如何使用CBC模式,并强调随机IV生成的重要性,以及如何通过`NewCBCEncrypter`和`NewCBCDecrypter`实现加密解密。同时,还将介绍RSA密钥对的生成与PEM格式导出,以及公钥加密和私钥解密的具体方法。此外,文章还包括SHA-256哈希值的生成,并提醒在密码存储时使用更安全的bcrypt或scrypt算法。掌握这些技巧,助您在Golang项目中安全地保护数据。
使用crypto/aes进行AES对称加密,需选择CBC模式并生成随机IV,加密时填充密文并使用NewCBCEncrypter,解密时用NewCBCDecrypter还原明文。

在Golang中,crypto包提供了多种加密算法的实现,可用于数据安全保护。要正确使用它,需根据具体需求选择合适的子包,如AES对称加密、RSA非对称加密或生成哈希值等。
使用crypto/aes进行对称加密
AES(高级加密标准)是常用的对称加密方式,加密和解密使用相同密钥。
以下是使用CBC模式进行AES加密的示例:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"io"
)
func encrypt(plaintext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
stream := cipher.NewCBCEncrypter(block, iv)
stream.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
return ciphertext, nil
}
func decrypt(ciphertext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(ciphertext) < aes.BlockSize {
return nil, err
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
stream := cipher.NewCBCDecrypter(block, iv)
stream.CryptBlocks(ciphertext, ciphertext)
return ciphertext, nil
}
注意:密钥长度必须是16、24或32字节(对应AES-128、AES-192、AES-256)。
使用crypto/rsa进行非对称加密
RSA适合加密小量数据或传输对称密钥。
生成密钥对并加密示例:
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
)
// 生成RSA私钥
func generatePrivateKey() (*rsa.PrivateKey, error) {
return rsa.GenerateKey(rand.Reader, 2048)
}
// 导出为PEM格式
func encodePrivateKey(key *rsa.PrivateKey) []byte {
privBytes := x509.MarshalPKCS1PrivateKey(key)
return pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: privBytes,
})
}
// 使用公钥加密
func encryptWithPublicKey(msg []byte, pub *rsa.PublicKey) ([]byte, error) {
return rsa.EncryptPKCS1v15(rand.Reader, pub, msg)
}
// 使用私钥解密
func decryptWithPrivateKey(ciphertext []byte, priv *rsa.PrivateKey) ([]byte, error) {
return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}
实际使用中,通常结合对称与非对称加密,例如用RSA加密AES密钥。
使用crypto/sha256生成哈希值
SHA-256常用于数据完整性校验。
package main
import (
"crypto/sha256"
"fmt"
)
func hashData(data []byte) []byte {
h := sha256.Sum256(data)
return h[:]
}
// 示例
func main() {
data := []byte("hello world")
hash := hashData(data)
fmt.Printf("%x\n", hash) // 输出十六进制哈希
}
该操作不可逆,适用于密码哈希存储(但建议使用bcrypt或scrypt增强安全性)。
基本上就这些。根据场景选择合适算法,注意密钥管理与初始化向量(IV)的随机性,避免重复使用IV,确保加密安全性。
好了,本文到此结束,带大家了解了《Golangcrypto加密使用详解》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
