go语言通过crypto包实现SHA256哈希与AES-GCM对称加密:先使用sha256.Sum256生成数据指纹,再利用aes.NewCipher和cipher.NewGCM进行加密解密,确保数据完整性与机密性。

Go语言通过标准库中的crypto包提供强大的加密功能,涵盖对称加密、非对称加密、哈希算法和数字签名等。实际开发中,合理使用这些工具能有效保障数据安全。
使用哈希算法(如SHA256)
哈希函数常用于生成数据指纹或校验值。以SHA256为例:
package main import ( "crypto/sha256" "fmt" ) func main() { data := []byte("hello world") hash := sha256.Sum256(data) fmt.Printf("SHA256: %xn", hash) }
说明:Sum256返回[32]byte固定长度数组,%x格式化输出为十六进制字符串。适合密码存储前的摘要处理。
对称加密:AES-GCM模式
AES是常用的对称加密算法,GCM模式提供认证加密,防止数据篡改。
立即学习“go语言免费学习笔记(深入)”;
<code>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 } gcm, err := cipher.NewGCM(block) if err != nil { return nil, err } nonce := make([]byte, gcm.NonceSize()) if _, err = io.ReadFull(rand.Reader, nonce); err != nil { return nil, err } ciphertext := gcm.Seal(nonce, nonce, plaintext, nil) return ciphertext, nil } func decrypt(ciphertext []byte, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } gcm, err := cipher.NewGCM(block) if err != nil { return nil, err } nonceSize := gcm.NonceSize() if len(ciphertext) < nonceSize { return nil, fmt.Errorf("ciphertext too short") } nonce, cipherdata := ciphertext[:nonceSize], ciphertext[nonceSize:] plaintext, err := gcm.Open(nil, nonce, cipherdata, nil) return plaintext, err }
关键点:
- 密钥长度支持16、24、32字节(对应AES-128/192/256)
- 每次加密使用随机nonce,确保相同明文生成不同密文
- 密文包含nonce+加密数据,需完整保存
非对称加密:RSA加解密与签名
RSA适用于密钥交换和数字签名。以下为签名与验证示例:
package main import ( "crypto/rand" "crypto/rsa" "crypto/sha256" "crypto/x509" "encoding/pem" "fmt" ) func sign(msg []byte, privKey *rsa.PrivateKey) ([]byte, error) { hash := sha256.Sum256(msg) return rsa.SignPKCS1v15(rand.Reader, privKey, crypto.SHA256, hash[:]) } func verify(msg, sig []byte, pubKey *rsa.PublicKey) error { hash := sha256.Sum256(msg) return rsa.VerifyPKCS1v15(pubKey, crypto.SHA256, hash[:], sig) }
操作建议:
- 私钥签名,公钥验证,用于身份认证
- 密钥建议2048位以上
- 实际应用中可通过pem包读写密钥文件
基本上就这些。日常开发优先选择AES-GCM和RSA组合方案,注意密钥安全管理,避免硬编码。crypto子包丰富,按需引入即可。


