AI创作问答(高级版)
在Go中实现基本的加密解密功能可以使用标准库中的crypto包。具体来说,可以使用crypto/rand生成随机密钥,然后使用crypto/cipher包中的AES算法进行加密解密操作。以下是一个示例代码:
```go
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
)
func main() {
key := generateRandomKey(32) // 生成32字节的随机密钥
plaintext := "Hello, World!"
fmt.Println("原始文本:", plaintext)
ciphertext, err := encrypt(key, []byte(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 generateRandomKey(length int) []byte {
key := make([]byte, length)
if _, err := io.ReadFull(rand.Reader, key); err != nil {
panic(err)
}
return key
}
// 使用AES算法进行加密
func encrypt(key, plaintext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
// 使用CBC模式加密
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
}
// 使用AES算法进行解密
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:]
// 使用CBC模式解密
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)
return ciphertext, nil
}
```
这段代码演示了如何使用AES算法进行加密解密操作。注意,这只是一个基本的示例,实际使用中还需要考虑更多的安全性和错误处理机制。