Go语言crypto包提供AES、RSA、SHA256等加密功能,示例展示AES-GCM对称加解密、RSA非对称加解密及HMAC-SHA256消息认证,强调安全模式与密钥管理。

Go语言的 crypto 包为常见的加密算法提供了标准接口和实现,广泛用于数据加密、解密、签名和哈希计算等安全场景。通过合理使用 crypto 包中的子包(如 crypto/aes、crypto/des、crypto/rsa、crypto/rand 等),可以高效实现对称加密、非对称加密以及安全随机数生成。
使用 crypto/aes 实现 AES 对称加密与解密
AES(Advanced Encryption Standard)是最常用的对称加密算法之一,支持 128、192 和 256 位密钥长度。Go 中通过 crypto/aes 和 crypto/cipher 包实现 AES 加密。
常见模式使用 CBC(Cipher Block Chaining)或 GCM(Galois/Counter Mode),以下是一个使用 AES-CBC 的示例:
package mainimport ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "fmt" "io")func encrypt(plaintext []byte, key []byte) (string, error) { block, err := aes.NewCipher(key) if err != nil { return "", err } gcm, err := cipher.NewGCM(block) if err != nil { return "", err } nonce := make([]byte, gcm.NonceSize()) if _, err = io.ReadFull(rand.Reader, nonce); err != nil { return "", err } ciphertext := gcm.Seal(nonce, nonce, plaintext, nil) return base64.StdEncoding.EncodeToString(ciphertext), nil}func decrypt(ciphertextStr string, key []byte) ([]byte, error) { data, err := base64.StdEncoding.DecodeString(ciphertextStr) if err != nil { return nil, err } 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(data) < nonceSize { return nil, fmt.Errorf("ciphertext too short") } nonce, ciphertext := data[:nonceSize], data[nonceSize:] return gcm.Open(nil, nonce, ciphertext, nil)}func main() { key := []byte("example key 1234") // 16字节密钥(AES-128) plaintext := []byte("Hello, this is a secret message!") encrypted, err := encrypt(plaintext, key) if err != nil { panic(err) } fmt.Printf("Encrypted: %sn", encrypted) decrypted, err := decrypt(encrypted, key) if err != nil { panic(err) } fmt.Printf("Decrypted: %sn", decrypted)}
说明:该示例使用 AES-GCM 模式,它提供认证加密(AEAD),比 CBC 更安全且无需单独处理填充。密钥必须是 16、24 或 32 字节(对应 AES-128/192/256)。
立即学习“go语言免费学习笔记(深入)”;
使用 crypto/rsa 实现 RSA 非对称加密
RSA 是一种非对称加密算法,适用于加密小量数据或传输对称密钥。Go 的 crypto/rsa 结合 crypto/rand 可实现公钥加密、私钥解密。
以下演示如何生成密钥对并进行加解密:
package mainimport ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" "fmt")func main() { // 生成 RSA 密钥对(2048位) privateKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { panic(err) } // 获取公钥 publicKey := &privateKey.PublicKey plaintext := []byte("This is a secret message only for RSA.") // 使用公钥加密 ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plaintext) if err != nil { panic(err) } fmt.Printf("Encrypted (base64): %sn", base64.StdEncoding.EncodeToString(ciphertext)) // 使用私钥解密 decrypted, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, ciphertext) if err != nil { panic(err) } fmt.Printf("Decrypted: %sn", decrypted)}
注意:RSA 只适合加密小于密钥长度的数据(减去填充)。实际应用中常用于加密 AES 密钥,而非原始数据。
使用 crypto/sha256 和 crypto/hmac 进行哈希与消息认证
数据完整性验证常使用 SHA-256 哈希和 HMAC 签名。Go 的 crypto/sha256 和 crypto/hmac 提供了简单接口。
示例:计算字符串 SHA256 哈希和 HMAC-SHA256:
package mainimport ( "crypto/hmac" "crypto/sha256" "encoding/hex" "fmt")func main() { data := "hello world" key := []byte("my-secret-key") // SHA256 哈希 hash := sha256.Sum256([]byte(data)) fmt.Printf("SHA256: %sn", hex.EncodeToString(hash[:])) // HMAC-SHA256 h := hmac.New(sha256.New, key) h.Write([]byte(data)) mac := h.Sum(nil) fmt.Printf("HMAC-SHA256: %sn", hex.EncodeToString(mac))}
HMAC 可防止哈希被篡改,常用于 API 签名、Token 验证等场景。
基本上就这些常用方法。Go 的 crypto 包设计清晰,配合标准库使用非常方便。只要注意密钥管理、模式选择和随机数安全,就能构建基本的安全通信机制。
以上就是Golang如何使用 crypto 包实现加密算法_Golang crypto 数据加密与解密方法的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1425732.html
微信扫一扫
支付宝扫一扫