请用golang写出aes加解密的方法
以下是使用Golang编写的AES加解密方法示例:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
)
func main() {
key := []byte("0123456789abcdef") // 16字节的AES密钥
plaintext := []byte("Hello, World!") // 要加密的明文
ciphertext, err := encrypt(key, plaintext)
if err != nil {
fmt.Println("加密失败:", err)
return
}
fmt.Println("密文:", base64.StdEncoding.EncodeToString(ciphertext))
decryptedText, err := decrypt(key, ciphertext)
if err != nil {
fmt.Println("解密失败:", err)
return
}
fmt.Println("解密后的明文:", string(decryptedText))
}
// 加密函数
func encrypt(key, plaintext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
return ciphertext, nil
}
// 解密函数
func decrypt(key, ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(ciphertext) < aes.BlockSize {
return nil, fmt.Errorf("密文太短")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)
return ciphertext, nil
}
在上面的示例中,我们使用AES-128加密算法,密钥长度为16字节。首先,我们定义了一个加密函数encrypt和一个解密函数decrypt。在加密函数中,我们生成一个随机的初始化向量(IV),然后使用CBC模式创建一个加密器,并将明文加密成密文。在解密函数中,我们使用相同的密钥和IV创建一个解密器,并将密文解密成明文。最后,我们使用main函数来测试加解密过程。
原文地址: https://www.cveoy.top/t/topic/ixLe 著作权归作者所有。请勿转载和采集!