使用crypto/sha256生成SHA256哈希值以验证数据完整性,输出64位十六进制字符串;2. 利用crypto/aes和crypto/cipher实现AES-CBC模式加解密,确保敏感数据安全。

Go语言标准库中的crypto包为开发者提供了丰富的加密和哈希功能,涵盖对称加密、非对称加密以及常见哈希算法。在实际开发中,合理使用这些工具能有效保障数据安全。下面通过几个典型场景,展示如何在Golang中进行加密与哈希操作。
哈希函数常用于校验数据完整性或存储密码摘要。SHA256是目前广泛使用的安全哈希算法之一。
以下代码演示如何对一段字符串生成SHA256哈希:
package main
import (
"crypto/sha256"
"fmt"
)
func main() {
data := "hello world"
hash := sha256.Sum256([]byte(data))
fmt.Printf("SHA256: %x\n", hash)
}
输出结果是一个64位的十六进制字符串。Sum256返回[32]byte数组,使用%x格式化可转换为小写十六进制表示。
立即学习“go语言免费学习笔记(深入)”;
AES(高级加密标准)是一种常用的对称加密算法,适用于加密敏感数据如用户信息、配置文件等。Go中通过crypto/aes和crypto/cipher实现。
以下示例使用AES-CBC模式进行加解密:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"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, fmt.Errorf("ciphertext too short")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
stream := cipher.NewCBCDecrypter(block, iv)
stream.CryptBlocks(ciphertext, ciphertext)
return ciphertext, nil
}
func main() {
key := []byte("example key 1234") // 16字节密钥(AES-128)
plaintext := []byte("this is secret")
encrypted, err := encrypt(plaintext, key)
if err != nil {
panic(err)
}
decrypted, err := decrypt(encrypted, key)
if err != nil {
panic(err)
}
fmt.Printf("原文: %s\n", plaintext)
fmt.Printf("密文: %x\n", encrypted)
fmt.Printf("解密后: %s\n", decrypted)
}
注意:密钥长度需符合AES要求(16、24或32字节分别对应AES-128/192/256)。初始化向量IV必须随机且每次不同,以增强安全性。
RSA适合密钥交换或数字签名场景。Go的crypto/rsa支持生成密钥对、加密和解密。
示例:生成RSA密钥并对数据加密:
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"log"
)
func main() {
// 生成私钥
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
log.Fatal(err)
}
// 公钥
publicKey := &privateKey.PublicKey
msg := []byte("secret message")
encrypted, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, msg)
if err != nil {
log.Fatal(err)
}
decrypted, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, encrypted)
if err != nil {
log.Fatal(err)
}
fmt.Printf("加密前: %s\n", msg)
fmt.Printf("解密后: %s\n", decrypted)
}
该例子使用PKCS#1 v1.5填充方案。生产环境建议使用OAEP(更安全),可通过rsa.EncryptOAEP和rsa.DecryptOAEP实现。
直接存储用户密码明文极不安全。推荐使用golang.org/x/crypto/bcrypt对密码进行哈希处理。
安装依赖:go get golang.org/x/crypto/bcrypt
package main
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
func main() {
password := []byte("mysecretpassword")
// 哈希密码
hashed, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
if err != nil {
panic(err)
}
fmt.Printf("哈希值: %s\n", hashed)
// 验证密码
err = bcrypt.CompareHashAndPassword(hashed, password)
if err == nil {
fmt.Println("密码匹配")
} else {
fmt.Println("密码错误")
}
}
bcrypt自动包含盐值(salt),避免彩虹表攻击,且计算成本可调,适合抵御暴力破解。
基本上就这些常用操作。掌握这些基础实践,可以在Go项目中安全地处理加密与哈希需求。关键是选择合适算法并正确实现细节,比如随机IV、足够强度的密钥和适当的填充模式。
以上就是Golang crypto加密与哈希操作实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号