package main

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"os"
)

func main() {
	// 生成随机的AES加密密钥
	key := make([]byte, 32)
	if _, err := rand.Read(key); err != nil {
		fmt.Println("Failed to generate AES key:", err)
		return
	}
	fmt.Println("Random AES key:", base64.StdEncoding.EncodeToString(key))

	// 读取本地文件payload.bin
	payload, err := ioutil.ReadFile("payload.bin")
	if err != nil {
		fmt.Println("Failed to read payload file:", err)
		return
	}

	// 对payload进行AES-CTR加密
	block, err := aes.NewCipher(key)
	if err != nil {
		fmt.Println("Failed to create AES cipher:", err)
		return
	}
	iv := make([]byte, aes.BlockSize)
	if _, err := rand.Read(iv); err != nil {
		fmt.Println("Failed to generate IV:", err)
		return
	}
	stream := cipher.NewCTR(block, iv)
	encrypted := make([]byte, len(payload))
	stream.XORKeyStream(encrypted, payload)

	// 打印加密的内容
	fmt.Println("Encrypted payload:", base64.StdEncoding.EncodeToString(encrypted))
	
	// 保存加密后的内容到文件encrypted.bin
	if err := ioutil.WriteFile("encrypted.bin", encrypted, 0644); err != nil {
		fmt.Println("Failed to write encrypted file:", err)
		return
	}
}
Go语言实现AES-CTR加密本地文件,生成随机密钥并Base64编码

原文地址: https://www.cveoy.top/t/topic/mj04 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录