golang 的 crypto 库支持多种加密算法,但需根据安全需求选择。1. md5 用于校验文件完整性,不适用于密码存储;2. aes 是对称加密算法,适合数据加密,需使用 gcm 模式并确保 nonce 唯一;3. 密码应使用 bcrypt 或 argon2 加盐哈希后存储;4. 安全随机数通过 crypto/rand 生成;5. 密钥应通过环境变量管理而非硬编码。务必遵循最佳实践以保障安全性。

Golang 的
crypto

使用 Golang 的
crypto

MD5 是一种哈希算法,用于生成数据的唯一指纹。虽然不适合加密,但可以用于数据校验。
立即学习“go语言免费学习笔记(深入)”;
package main
import (
"crypto/md5"
"fmt"
"encoding/hex"
)
func main() {
data := "Hello, world!"
hash := md5.Sum([]byte(data))
md5String := hex.EncodeToString(hash[:])
fmt.Println("MD5 Hash:", md5String)
}这段代码首先导入了
crypto/md5
encoding/hex
hash[:]

AES 是一种对称加密算法,使用相同的密钥进行加密和解密。
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"log"
)
func main() {
key := []byte("passphrasewhichneedstobe32bytes!") // AES-256 密钥,必须是 32 字节
plaintext := []byte("This is some plaintext data.")
ciphertext, err := encrypt(key, plaintext)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Ciphertext: %x\n", ciphertext)
decryptedtext, err := decrypt(key, ciphertext)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Decrypted: %s\n", decryptedtext)
}
func encrypt(key, plaintext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
// GCM (Galois/Counter Mode) 是一种 authenticated encryption algorithm
// 提供 confidentiality 和 integrity
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, aesGCM.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
ciphertext := aesGCM.Seal(nonce, nonce, plaintext, nil)
return ciphertext, nil
}
func decrypt(key, ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonceSize := aesGCM.NonceSize()
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
plaintext, err := aesGCM.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return plaintext, nil
}这段代码展示了 AES 加密和解密的完整流程。关键点包括:
cipher.NewGCM
aesGCM.Seal
aesGCM.Open
选择加密算法取决于你的安全需求和性能要求。
通常,我们会结合使用不同的加密算法。例如,可以使用 RSA 加密 AES 密钥,然后使用 AES 加密数据。
永远不要直接存储密码!应该使用哈希算法(如 bcrypt 或 Argon2)加盐后存储。
package main
import (
"fmt"
"golang.org/x/crypto/bcrypt"
"log"
)
func main() {
password := "mysecretpassword"
hashedPassword, err := hashPassword(password)
if err != nil {
log.Fatal(err)
}
fmt.Println("Hashed Password:", hashedPassword)
err = comparePassword(password, hashedPassword)
if err != nil {
fmt.Println("Password mismatch:", err)
} else {
fmt.Println("Password matched!")
}
}
func hashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return string(bytes), err
}
func comparePassword(password, hashedPassword string) error {
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
return err
}这段代码使用了
golang.org/x/crypto/bcrypt
bcrypt.GenerateFromPassword
bcrypt.CompareHashAndPassword
使用
crypto/rand
package main
import (
"crypto/rand"
"fmt"
"io"
"log"
)
func main() {
b := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, b); err != nil {
log.Fatal(err)
}
fmt.Printf("Random bytes: %x\n", b)
}这段代码生成了 32 字节的随机数。
io.ReadFull(rand.Reader, b)
不要在代码中硬编码密钥!应该使用环境变量来管理密钥。
package main
import (
"fmt"
"os"
)
func main() {
apiKey := os.Getenv("API_KEY")
if apiKey == "" {
fmt.Println("API_KEY not set")
} else {
fmt.Println("API_KEY:", apiKey)
}
}这段代码从环境变量
API_KEY
os.Setenv
总而言之,
crypto
以上就是Golang的crypto库如何实现加密解密 演示MD5与AES算法应用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号