2025-04-23 10:01:05 +08:00

56 lines
1.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.IO;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;
public class EncryptFileCreator
{
private static byte[] key = Encoding.UTF8.GetBytes("Sixteen byte key"); // 加密密钥需16字节
private static byte[] iv = Encoding.UTF8.GetBytes("InitializationVe"); // 确保IV长度为16字节
public static void EncryptAndSaveData(string data,string path)
{
string filePath = Path.Combine(Application.streamingAssetsPath, path);
if (!File.Exists(filePath))
{
try
{
// 创建文件
File.WriteAllText(filePath, "");
Debug.Log("文件已创建");
}
catch (IOException e)
{
Debug.LogError($"创建文件时出错: {e.Message}");
}
}
// 将数据转换为字节数组
byte[] plainText = Encoding.UTF8.GetBytes(data);
// 创建AES加密器
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = key;
aesAlg.IV = iv;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// 创建内存流和加密流
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
csEncrypt.Write(plainText, 0, plainText.Length);
csEncrypt.FlushFinalBlock();
// 获取加密后的数据
byte[] encryptedData = msEncrypt.ToArray();
// 保存加密文件到StreamingAssets文件夹
string fullPath = Path.Combine(Application.streamingAssetsPath, filePath);
File.WriteAllBytes(fullPath, encryptedData);
}
}
}
}
}