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

Go语言通过标准库中的crypto包提供强大的加密功能,涵盖对称加密、非对称加密、哈希算法和数字签名等。实际开发中,合理使用这些工具能有效保障数据安全。
哈希函数常用于生成数据指纹或校验值。以SHA256为例:
package main
import (
"crypto/sha256"
"fmt"
)
func main() {
data := []byte("hello world")
hash := sha256.Sum256(data)
fmt.Printf("SHA256: %x\n", hash)
}
说明:Sum256返回[32]byte固定长度数组,%x格式化输出为十六进制字符串。适合密码存储前的摘要处理。
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
}
关键点:
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)
}
操作建议:
基本上就这些。日常开发优先选择AES-GCM和RSA组合方案,注意密钥安全管理,避免硬编码。crypto子包丰富,按需引入即可。
以上就是Golang如何使用crypto进行加密操作的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号