Go语言crypto包支持SHA-256哈希、AES对称加密和RSA非对称加密;通过sha256.Sum256计算摘要,aes.NewCipher配合cipher.NewCBCEncrypter实现AES加密,rsa.GenerateKey生成密钥对并使用EncryptPKCS1v15进行RSA加密,适用于数据安全、完整性校验与密钥交换场景。

Go语言的crypto包提供了多种加密算法的支持,包括对称加密、非对称加密、哈希函数和数字签名等。实际开发中,合理使用这些工具能有效保障数据安全。下面通过常见场景说明如何在Golang中使用crypto包进行加密操作。
SHA-256是常用的哈希算法,适用于密码存储、数据完整性校验等场景。
示例:计算字符串的SHA-256值代码实现:
使用sha256.Sum256()可以直接得到[32]byte类型的摘要,转为十六进制字符串便于展示。
package main
import (
"crypto/sha256"
"fmt"
)
func main() {
data := []byte("hello world")
hash := sha256.Sum256(data)
fmt.Printf("%x\n", hash) // 输出: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
}
AES(高级加密标准)是最广泛使用的对称加密算法之一,适合加密大量数据。
关键点:
需要密钥长度为16、24或32字节(分别对应AES-128、AES-192、AES-256),并选择合适的加密模式如CBC或GCM。
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
}
blockSize := block.BlockSize()
plaintext = pad(plaintext, blockSize)
ciphertext := make([]byte, blockSize+len(plaintext))
iv := ciphertext[:blockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[blockSize:], plaintext)
return ciphertext, nil
}
func pad(data []byte, blockSize int) []byte {
padding := blockSize - len(data)%blockSize
padtext := make([]byte, padding)
for i := range padtext {
padtext[i] = byte(padding)
}
return append(data, padtext...)
}
func main() {
key := []byte("example key 1234") // 16字节密钥
plaintext := []byte("this is a secret message")
ciphertext, _ := encrypt(plaintext, key)
fmt.Printf("Encrypted: %x\n", ciphertext)
}
RSA常用于安全通信中的密钥交换或数字签名,公钥加密,私钥解密。
立即学习“go语言免费学习笔记(深入)”;
示例:生成RSA密钥并对数据加密说明:
使用rsa.GenerateKey生成密钥对,利用公钥加密,私钥可后续用于解密。
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"os"
)
func generateRSAKey() {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
panic(err)
}
derStream := x509.MarshalPKCS1PrivateKey(privateKey)
block := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: derStream,
}
pemfile, _ := os.Create("private.pem")
pem.Encode(pemfile, block)
pemfile.Close()
publicKey := &privateKey.PublicKey
pubDer, _ := x509.MarshalPKIXPublicKey(publicKey)
pubBlock := &pem.Block{
Type: "PUBLIC KEY",
Bytes: pubDer,
}
pubFile, _ := os.Create("public.pem")
pem.Encode(pubFile, pubBlock)
pubFile.Close()
}
func encryptWithPubKey(msg []byte, pub *rsa.PublicKey) ([]byte, error) {
return rsa.EncryptPKCS1v15(rand.Reader, pub, msg)
}
func main() {
generateRSAKey()
fmt.Println("RSA密钥已生成")
}
上述代码会生成private.pem和public.pem两个文件,可用于后续加解密流程。
基本上就这些常见用法。实际项目中注意密钥管理、填充模式选择以及避免硬编码敏感信息。crypto包设计严谨,配合标准库使用非常方便。
以上就是Golang如何使用crypto包实现加密_Golang crypto加密实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号