using System.IO;
using System.Text;
using System.Security.Cryptography;
using UnityEngine;

namespace Comgreate
{
    public class AESForFileKit
    {
        private static readonly byte[] Salt = Encoding.UTF8.GetBytes("Sgfsads");


        private const int Iterations = 1000;


        public static void EncryptFile(string inputPath, string outputPath, string password)
        {
            var passwordBytes = Encoding.UTF8.GetBytes(password);
            var inputStream = new FileStream(inputPath, FileMode.Open, FileAccess.Read);
            var outputStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write);

            using var aes = new AesManaged();
            var key = new Rfc2898DeriveBytes(passwordBytes, Salt, Iterations);
            aes.Key = key.GetBytes(aes.KeySize / 8);
            aes.IV = key.GetBytes(aes.BlockSize / 8);
            using var cryptoStream = new CryptoStream(outputStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
            inputStream.CopyTo(cryptoStream);
            cryptoStream.FlushFinalBlock();
            cryptoStream.Close();
            outputStream.Close();
            inputStream.Close();
        }


        public static byte[] DecryptToBytes(string inputPath, string password, out int dataSize)
        {
            var passwordBytes = Encoding.UTF8.GetBytes(password);
            var inputStream = new FileStream(inputPath, FileMode.Open, FileAccess.Read);
            var outputMemoryStream = new MemoryStream();

            using (var aes = new AesManaged())
            {
                var key = new Rfc2898DeriveBytes(passwordBytes, Salt, Iterations);
                aes.Key = key.GetBytes(aes.KeySize / 8);
                aes.IV = key.GetBytes(aes.BlockSize / 8);
                using (var cryptoStream = new CryptoStream(inputStream, aes.CreateDecryptor(), CryptoStreamMode.Read))
                {
                    cryptoStream.CopyTo(outputMemoryStream);
                }
            }

            var outputBytes = outputMemoryStream.ToArray();
            dataSize = outputBytes.Length;
            return outputBytes;
        }
    }
}