stream.XORKeyStream(ciphertext[aes.BlockSize:], []byte(records))报错无法将[][]string转为[]byte怎么办写出完整代码
时间: 2023-09-25 20:13:42 浏览: 144
好的,这里是修改后的代码:
```
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/csv"
"os"
"io"
"log"
"bytes"
)
func SaveOS() {
var data []model.HistoryMessages
gorm.DB.Find(&data)
// 创建文件并打开
file, err := os.Create("data.csv")
if err != nil {
panic(err)
}
defer file.Close()
// 创建CSV writer
writer := csv.NewWriter(file)
defer writer.Flush()
// 写入表头
writer.Write([]string{"SendId", "ReceiveId", "Object", "Media", "Content", "SendTime"})
// 写入数据
for _, message := range data {
record := []string{
message.SendId,
message.ReceiveId,
message.Object,
message.Media,
message.Content,
message.SendTime.Format("2006-01-02 15:04:05"),
}
writer.Write(record)
}
// 打开CSV文件并读取数据
csvfile, err := os.Open("data.csv")
if err != nil {
log.Fatalln("Unable to read input file " + "data.csv")
}
defer csvfile.Close()
reader := csv.NewReader(csvfile)
records, err := reader.ReadAll()
if err != nil {
log.Fatalln("Unable to parse file " + "data.csv")
}
// 生成随机密钥和向量
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
panic(err.Error())
}
iv := make([]byte, aes.BlockSize)
if _, err := rand.Read(iv); err != nil {
panic(err.Error())
}
// 创建加密器
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
var plaintext bytes.Buffer
writer = csv.NewWriter(&plaintext)
writer.WriteAll(records)
plaintextBytes := plaintext.Bytes()
ciphertext := make([]byte, aes.BlockSize+len(plaintextBytes))
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintextBytes)
// 写入加密后的数据和密钥、向量到文件
outfile, err := os.Create("data.enc")
if err != nil {
log.Fatalln("Unable to create output file " + "data.enc")
}
defer outfile.Close()
// 写入密钥和向量
outfile.Write(iv)
outfile.Write(key)
// 写入加密后的数据
_, err = outfile.Write(ciphertext)
if err != nil {
log.Fatalln("Unable to write encrypted data to output file")
}
}
```
在这个代码中,我们首先将 CSV 数据写入到内存中的一个 buffer 中,然后将 buffer 转换成 []byte 类型,然后再对它进行加密。这样就可以避免将 [][]string 类型的 records 直接传给 XORKeyStream 函数导致的类型错误。
阅读全文