golang aes256加密
以下是使用Golang进行AES256加密的示例:
package main
import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
)
func main() {
// 要加密的原始数据
plaintext := []byte("hello world")
// 32位密钥,AES256加密需要32位(256位)密钥
key := []byte("12345678901234567890123456789012")
// 创建AES加密器
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
// 生成随机的IV向量
iv := make([]byte, aes.BlockSize)
if _, err := rand.Read(iv); err != nil {
panic(err)
}
// 使用CBC分组模式进行加密
cipherText := make([]byte, len(plaintext))
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(cipherText, plaintext)
// 将IV向量和密文合并,方便后续解密
result := append(iv, cipherText...)
// 将密文转换为base64编码的字符串,方便传输和存储
base64Text := base64.StdEncoding.EncodeToString(result)
fmt.Println(base64Text)
}
在上面的示例中,我们使用AES256加密算法和CBC分组模式对字符串“hello world”进行加密。我们使用一个32位(256位)的密钥,并生成一个随机的IV向量。最终,我们将IV向量和密文合并,并将密文转换为base64编码的字符串以便传输和存储。
请注意,我们使用了Go标准库中的crypto/aes和crypto/cipher包来完成AES256加密。我们还使用了encoding/base64包将密文转换为base64编码的字符串
原文地址: https://www.cveoy.top/t/topic/em4q 著作权归作者所有。请勿转载和采集!