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

namespace LauncherUpdater.Function
{
    public static class EncryptionHelper
    {
        public static string Encrypt(string clearText)
        {
            const string password = "N1PEUPQX";
            var bytes = Encoding.Unicode.GetBytes(clearText);
            using (var aes = Aes.Create())
            {
                var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, new byte[]
                {
                    73,
                    118,
                    97,
                    110,
                    32,
                    77,
                    101,
                    100,
                    118,
                    101,
                    100,
                    101,
                    118
                });
                aes.Key = rfc2898DeriveBytes.GetBytes(32);
                aes.IV = rfc2898DeriveBytes.GetBytes(16);
                using (var memoryStream = new MemoryStream())
                {
                    using (
                        var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write)
                    )
                    {
                        cryptoStream.Write(bytes, 0, bytes.Length);
                        cryptoStream.Close();
                    }

                    clearText = Convert.ToBase64String(memoryStream.ToArray());
                }
            }

            return clearText;
        }

        public static string Decrypt(string cipherText)
        {
            const string password = "N1PEUPQX";
            cipherText = cipherText.Replace(" ", "+");
            var buffer = Convert.FromBase64String(cipherText);
            using (var aes = Aes.Create())
            {
                var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, new byte[]
                {
                    73,
                    118,
                    97,
                    110,
                    32,
                    77,
                    101,
                    100,
                    118,
                    101,
                    100,
                    101,
                    118
                });
                aes.Key = rfc2898DeriveBytes.GetBytes(32);
                aes.IV = rfc2898DeriveBytes.GetBytes(16);
                using (var memoryStream = new MemoryStream())
                {
                    using (
                        var cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write)
                    )
                    {
                        cryptoStream.Write(buffer, 0, buffer.Length);
                        cryptoStream.Close();
                    }

                    cipherText = Encoding.Unicode.GetString(memoryStream.ToArray());
                }
            }

            return cipherText;
        }
    }
}