在Go语言中,crypto包提供了许多加密和解密算法的实现,包括对称加密、非对称加密、哈希函数等。
一、对称加密(AES算法)
1、加密数据
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
func main() {
// 生成随机密钥
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
panic(err)
}
plaintext := []byte("Hello, AES!")
// 创建AES加密块
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
// 使用CTR模式进行加密
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
panic(err)
}
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
fmt.Printf("Plaintext: %s\n", plaintext)
fmt.Printf("Ciphertext: %x\n", ciphertext)
}
解释:
这个例子中,使用AES算法对字符串 “Hello, AES!” 进行加密。生成随机密钥,使用CTR模式创建加密块,然后对明文进行加密。
2、解密数据
package main
import (
"crypto/aes"
"crypto/cipher"
"fmt"</

本文介绍了如何在Go语言中使用AES对称加密、RSA非对称加密以及SHA-256哈希函数,并展示了加密、解密和数字签名的基本操作。
最低0.47元/天 解锁文章
743

被折叠的 条评论
为什么被折叠?



