Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.IO;
- using System.Security.Cryptography;
- using UnityEngine;
- public class FileEncryption : MonoBehaviour
- {
- private string encryptionKey = "your_secure_key";
- void Start()
- {
- string filePath = Application.dataPath + "/YourImportantFile.txt";
- EncryptFile(filePath);
- DecryptFile(filePath);
- }
- void EncryptFile(string filePath)
- {
- try
- {
- using (Aes aes = Aes.Create())
- {
- aes.Key = System.Text.Encoding.UTF8.GetBytes(encryptionKey.PadRight(32));
- aes.IV = new byte[16]; // 16 bytes for AES initialization vector (can be random)
- using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate))
- using (CryptoStream cryptoStream = new CryptoStream(fileStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
- {
- byte[] fileBytes = File.ReadAllBytes(filePath);
- cryptoStream.Write(fileBytes, 0, fileBytes.Length);
- }
- }
- Debug.Log("File encrypted.");
- }
- catch (System.Exception e)
- {
- Debug.LogError("Error encrypting file: " + e.Message);
- }
- }
- void DecryptFile(string filePath)
- {
- try
- {
- using (Aes aes = Aes.Create())
- {
- aes.Key = System.Text.Encoding.UTF8.GetBytes(encryptionKey.PadRight(32));
- aes.IV = new byte[16];
- using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
- using (CryptoStream cryptoStream = new CryptoStream(fileStream, aes.CreateDecryptor(), CryptoStreamMode.Read))
- {
- byte[] fileBytes = new byte[fileStream.Length];
- cryptoStream.Read(fileBytes, 0, fileBytes.Length);
- File.WriteAllBytes(filePath, fileBytes);
- }
- }
- Debug.Log("File decrypted.");
- }
- catch
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement