跳转到主内容
趣航编程网 - 趣学编程,启航技术之路!

Golang如何使用 crypto 包实现加密算法_Golang crypto 数据加密与解密方法

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 main import ( "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: %s\n", encrypted) decrypted, err := decrypt(encrypted, key) if err != nil { panic(err) } fmt.Printf("Decrypted: %s\n", decrypted) }
说明:该示例使用 AES-GCM 模式,它提供认证加密(AEAD),比 CBC 更安全且无需单独处理填充。密钥必须是 16、24 或 32 字节 (对应 AES-128/192/256)。 立即学习 “ go语言免费学习笔记(深入) ”; 使用 crypto/rsa 实现 RSA 非对称加密 RSA 是一种非对称加密算法,适用于加密小量数据或传输对称密钥。Go 的 crypto/rsa 结合 crypto/rand 可实现公钥加密、私钥解密。 以下演示如何生成密钥对并进行加解密: 通义灵码 Mac版 通义灵码 Mac版是阿里云推出的一款AI智能编码助手,深度集成于Xcode、VS Code及JetBrains等主流IDE中。它基于大模型技术,支持行级/函数级实时续写、自然语言生成代码、单元测试生成及智能问答等核心功能。macOS用户可通过插件市场直接安装,开箱即用,旨在辅助开发者高效完成编码任务,提升研发效率。 下载
package main import ( "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): %s\n", base64.StdEncoding.EncodeToString(ciphertext)) // 使用私钥解密 decrypted, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, ciphertext) if err != nil { panic(err) } fmt.Printf("Decrypted: %s\n", decrypted) }
注意:RSA 只适合加密小于密钥长度的数据(减去填充)。实际应用中常用于加密 AES 密钥,而非原始数据。 使用 crypto/sha256 和 crypto/h mac 进行哈希与消息认证 数据完整性验证常使用 SHA-256 哈希和 HMAC 签名。Go 的 crypto/sha256 和 crypto/hmac 提供了简单接口。 示例:计算字符串 SHA256 哈希和 HMAC-SHA256:
package main import ( "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: %s\n", hex.EncodeToString(hash[:])) // HMAC-SHA256 h := hmac.New(sha256.New, key) h.Write([]byte(data)) mac := h.Sum(nil) fmt.Printf("HMAC-SHA256: %s\n", hex.EncodeToString(mac)) }
HMAC 可防止哈希被篡改,常用于 API 签名、Token 验证等场景。 基本上就这些常用方法。Go 的 crypto 包设计清晰,配合 标准库 使用非常方便。只要注意密钥管理、模式选择和随机数安全,就能构建基本的安全通信机制。

相关文章