Beispiel #1
0
        // кнопка для открытия (чтобы не прописывать в конструкторе)
        private void Open_Click(object sender, EventArgs e)
        {
            Open.Enabled   = false;
            label1.Visible = true;
            // проверка работает ли bluetooth
            if (BluetoothRadio.IsSupported)
            {
                // проверка расширения
                string k = Path.GetExtension(path);
                if (k == ".code3")
                {
                    // закрыываем кнопку
                    Open.Enabled = false;
                    // дезериализуем ключ и файл
                    DataContractJsonSerializer json2 = new DataContractJsonSerializer(typeof(Connectwithakey));
                    DataContractJsonSerializer json  = new DataContractJsonSerializer(typeof(ToCode));
                    FileStream st = null;
                    if (File.Exists(path))
                    {
                        try
                        {
                            st = new FileStream(path, FileMode.Open);
                        }
                        catch (IOException ex)
                        {
                            Console.WriteLine("Try again");
                        }
                        try
                        {
                            Connectwithakey con = null;
                            con           = (Connectwithakey)json2.ReadObject(st);
                            FindkeyNumber = con.file;
                            // номер ключа
                            this.num = int.Parse(Encoding.ASCII.GetString(con.keynumber));
                            st.Close();
                            byte[] serkey = null;
                            // извлечение ключа из файла
                            if (File.Exists($"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/Pakman{num}.txt"))
                            {
                                serkey = File.ReadAllBytes($"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/Pakman{num}.txt");
                                IntPtr          accountToken = WindowsIdentity.GetCurrent().Token;
                                WindowsIdentity win          = new WindowsIdentity(accountToken);
                                // раскодируем
                                ID = win.User.ToString();
                                // ксорим с id в ASCII
                                byte[] tocodekey = Encoding.ASCII.GetBytes(ID);
                                int    q         = 0;
                                for (int i = 0; i < serkey.Length; i++)
                                {
                                    if (q == tocodekey.Length)
                                    {
                                        q = 0;
                                    }
                                    serkey[i] = (byte)(serkey[i] ^ tocodekey[q]);
                                }
                                // создём вспомогательный файл для десериализации и извдечение полей класса
                                string help;
                                if (Directory.Exists($"C:/Users/{Environment.UserName}/AppData/Roaming"))
                                {
                                    help = $"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/Pakman{num}Help.txt";
                                }
                                else
                                {
                                    help = $"../Pakman{num}Help.txt";
                                }
                                // файл нужен для десериализации (так быстрее чем с memorystream так как есть writeallbytes)
                                File.Create(help).Close();
                                File.WriteAllBytes(help, serkey);
                                FileStream l = new FileStream(help, FileMode.Open);
                                cod = (ToCode)json.ReadObject(l);
                                l.Close();
                                // удаляем вспомогательный файл
                                File.Delete(help);
                                // проверяем совпадение устройста
                                devicename   = cod.DeviceName;
                                deviceadress = cod.DeviceAdress;
                                // компонента bluetooth
                                BluetoothComponent component = new BluetoothComponent();
                                // добавляем метод который будет сделать если найдено новое устройство
                                component.DiscoverDevicesProgress += BluetoothDescovery;
                                // метод в конце работы
                                component.DiscoverDevicesComplete += BluetoothEndDescovery;
                                // поиск устройства
                                component.DiscoverDevicesAsync(10, true, false, true, true, 0);
                            }
                            else
                            {
                                if (File.Exists($"../Palon/Pakman{num}.txt"))
                                {
                                    serkey = File.ReadAllBytes($"../Palon/Pakman{num}.txt");

                                    IntPtr          accountToken = WindowsIdentity.GetCurrent().Token;
                                    WindowsIdentity win          = new WindowsIdentity(accountToken);
                                    // раскодируем
                                    ID = win.User.ToString();
                                    // ксорим с id в ASCII
                                    byte[] tocodekey = Encoding.ASCII.GetBytes(ID);
                                    int    q         = 0;
                                    for (int i = 0; i < serkey.Length; i++)
                                    {
                                        if (q == tocodekey.Length)
                                        {
                                            q = 0;
                                        }
                                        serkey[i] = (byte)(serkey[i] ^ tocodekey[q]);
                                    }
                                    // создём вспомогательный файл для десериализации и извдечение полей класса
                                    string help;
                                    if (Directory.Exists($"C:/Users/{Environment.UserName}/AppData/Roaming"))
                                    {
                                        help = $"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/Pakman{num}Help.txt";
                                    }
                                    else
                                    {
                                        help = $"../Pakman{num}Help.txt";
                                    }
                                    // файл нужен для десериализации (так быстрее чем с memorystream так как есть writeallbytes)
                                    File.Create(help).Close();
                                    File.WriteAllBytes(help, serkey);
                                    FileStream l = new FileStream(help, FileMode.Open);
                                    cod = (ToCode)json.ReadObject(l);
                                    l.Close();
                                    // удаляем вспомогательный файл
                                    File.Delete(help);
                                    // проверяем совпадение устройста
                                    devicename   = cod.DeviceName;
                                    deviceadress = cod.DeviceAdress;
                                    // компонента bluetooth
                                    BluetoothComponent component = new BluetoothComponent();
                                    // добавляем метод который будет сделать если найдено новое устройство
                                    component.DiscoverDevicesProgress += BluetoothDescovery;
                                    // метод в конце работы
                                    component.DiscoverDevicesComplete += BluetoothEndDescovery;
                                    // поиск устройства
                                    component.DiscoverDevicesAsync(10, true, false, true, true, 0);
                                }
                                else
                                {
                                    MessageBox.Show("Something has happened with keys");
                                    this.Close();
                                }
                            }
                            //безопастность (учетная запись)
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Two programms are trying to encript file");
                            this.Close();
                        }
                    }
                    else
                    {
                        MessageBox.Show("Two programms are trying to encript file");
                        this.Close();
                    }
                }
                else
                {
                    DataContractJsonSerializer json2 = new DataContractJsonSerializer(typeof(Connectwithakey));
                    DataContractJsonSerializer json  = new DataContractJsonSerializer(typeof(ToCode));
                    // десереализуем файл
                    FileStream st = null;
                    if (File.Exists(path))
                    {
                        try
                        {
                            st = new FileStream(path, FileMode.Open);
                            Connectwithakey con = null;
                            con           = (Connectwithakey)json2.ReadObject(st);
                            FindkeyNumber = con.file;
                            // номер ключа
                            this.num = int.Parse(Encoding.ASCII.GetString(con.keynumber));
                            st.Close();
                            // извлечение ключа из файла
                            byte[] serkey = null;
                            // извлечение ключа из файла
                            if (File.Exists($"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/PakmanD{num}.txt"))
                            {
                                serkey = File.ReadAllBytes($"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/PakmanD{num}.txt");
                            }
                            else
                            {
                                if (File.Exists($"../Palon/PakmanD{num}.txt"))
                                {
                                    serkey = File.ReadAllBytes($"../Palon/PakmanD{num}.txt");
                                }
                                else
                                {
                                    MessageBox.Show("Something has happened with keys");
                                    this.Close();
                                }
                            }
                            //безопастность (учетная запись)
                            IntPtr          accountToken = WindowsIdentity.GetCurrent().Token;
                            WindowsIdentity win          = new WindowsIdentity(accountToken);
                            // раскодируем ксоря c ID в ASCII
                            ID = win.User.ToString();
                            byte[] tocodekey = Encoding.ASCII.GetBytes(ID);
                            int    q         = 0;
                            for (int i = 0; i < serkey.Length; i++)
                            {
                                if (q == tocodekey.Length)
                                {
                                    q = 0;
                                }
                                serkey[i] = (byte)(serkey[i] ^ tocodekey[q]);
                            }
                            // создём вспомогательный файл для десериализации и извдечение полей класса
                            string help;
                            if (Directory.Exists($"C:/Users/{Environment.UserName}/AppData/Roaming"))
                            {
                                help = $"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/PakmanD{num}Help.txt";
                            }
                            else
                            {
                                help = $"../PakmanD{num}Help.txt";
                            }
                            // перезаписываем файл для десериализации так удобней чем при memorystream так как writeallbytes
                            File.Create(help).Close();
                            File.WriteAllBytes(help, serkey);
                            FileStream l = new FileStream(help, FileMode.Open);
                            cod = (ToCode)json.ReadObject(l);
                            l.Close();
                            // удаляем вспомогательный файл
                            File.Delete(help);
                            // проверяем совпадение устройста
                            devicename   = cod.DeviceName;
                            deviceadress = cod.DeviceAdress;
                            // создаём компоненту поиска
                            BluetoothComponent component = new BluetoothComponent();
                            // добавляем метод при каждом нахождении нового устройствва
                            component.DiscoverDevicesProgress += BluetoothDescovery;
                            // метод в конце поиска
                            component.DiscoverDevicesComplete += BluetoothEndDescovery;
                            // начало писка
                            component.DiscoverDevicesAsync(10, true, false, true, true, 0);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Two programms are trying to encript file");
                            this.Close();
                        }
                    }
                    else
                    {
                        MessageBox.Show("Two programms are trying to encript file");
                        this.Close();
                    }
                }
            }
            // раскодируем по паролю
            else
            {
                // аналогично смотрим расширение
                string k = Path.GetExtension(path);
                if (k == ".code3")
                {
                    // откючаем кнопку
                    Open.Enabled = false;
                    DataContractJsonSerializer json2 = new DataContractJsonSerializer(typeof(Connectwithakey));
                    DataContractJsonSerializer json  = new DataContractJsonSerializer(typeof(ToCode));
                    // десериализуем основной файл
                    FileStream st = null;
                    if (File.Exists(path))
                    {
                        try
                        {
                            st = new FileStream(path, FileMode.Open);
                            Connectwithakey con = null;
                            con           = (Connectwithakey)json2.ReadObject(st);
                            FindkeyNumber = con.file;
                            // номер ключа
                            this.num = int.Parse(Encoding.ASCII.GetString(con.keynumber));
                            st.Close();
                            // извлечение ключа из файла
                            byte[] serkey = null;
                            // извлечение ключа из файла
                            if (File.Exists($"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/Pakman{num}.txt"))
                            {
                                serkey = File.ReadAllBytes($"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/Pakman{num}.txt");
                            }
                            else
                            {
                                if (File.Exists($"../Palon/Pakman{num}.txt"))
                                {
                                    serkey = File.ReadAllBytes($"../Palon/Pakman{num}.txt");
                                }
                                else
                                {
                                    MessageBox.Show("Something has happened with keys");
                                    this.Close();
                                }
                            }
                            //безопастность (учетная запись)
                            IntPtr          accountToken = WindowsIdentity.GetCurrent().Token;
                            WindowsIdentity win          = new WindowsIdentity(accountToken);
                            // раскодируем ксоря с id ASCII
                            ID = win.User.ToString();
                            byte[] tocodekey = Encoding.ASCII.GetBytes(ID);
                            int    q         = 0;
                            for (int i = 0; i < serkey.Length; i++)
                            {
                                if (q == tocodekey.Length)
                                {
                                    q = 0;
                                }
                                serkey[i] = (byte)(serkey[i] ^ tocodekey[q]);
                            }
                            // создём вспомогательный файл для десериализации и извдечение полей класса
                            string help;
                            if (Directory.Exists($"C:/Users/{Environment.UserName}/AppData/Roaming"))
                            {
                                help = $"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/Pakman{num}Help.txt";
                            }
                            else
                            {
                                help = $"../Pakman{num}Help.txt";
                            }
                            File.Create(help).Close();
                            File.WriteAllBytes(help, serkey);
                            FileStream l = new FileStream(help, FileMode.Open);
                            cod = (ToCode)json.ReadObject(l);
                            l.Close();
                            // удаляем вспомогательный файл
                            File.Delete(help);
                            // проверяем совпадение устройста
                            devicename   = cod.DeviceName;
                            deviceadress = cod.DeviceAdress;
                            // если устройства нет рядом просим ввести пароль
                            NotFoundCheckingPassword password = new NotFoundCheckingPassword(cod);
                            password.ShowDialog();
                            // проверка верности пароля
                            if (password.Pasbool)
                            {
                                Redeem();
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Two programms are trying to encript file");
                            this.Close();
                        }
                    }
                    else
                    {
                        MessageBox.Show("Two programms are trying to encript file");
                        this.Close();
                    }
                }
                else
                {
                    // десериализуем основной файл
                    DataContractJsonSerializer json2 = new DataContractJsonSerializer(typeof(Connectwithakey));
                    DataContractJsonSerializer json  = new DataContractJsonSerializer(typeof(ToCode));
                    FileStream st = null;
                    if (File.Exists(path))
                    {
                        try
                        {
                            st = new FileStream(path, FileMode.Open);
                            Connectwithakey con = null;
                            con           = (Connectwithakey)json2.ReadObject(st);
                            FindkeyNumber = con.file;
                            // номер ключа
                            this.num = int.Parse(Encoding.ASCII.GetString(con.keynumber));
                            st.Close();
                            // извлечение ключа из файла
                            byte[] serkey = null;
                            // извлечение ключа из файла
                            if (File.Exists($"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/PakmanD{num}.txt"))
                            {
                                serkey = File.ReadAllBytes($"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/PakmanD{num}.txt");
                            }
                            else
                            {
                                if (File.Exists($"../Palon/PakmanD{num}.txt"))
                                {
                                    serkey = File.ReadAllBytes($"../Palon/PakmanD{num}.txt");
                                }
                                else
                                {
                                    MessageBox.Show("Something has happened with keys");
                                    this.Close();
                                }
                            }//безопастность (учетная запись)
                            IntPtr          accountToken = WindowsIdentity.GetCurrent().Token;
                            WindowsIdentity win          = new WindowsIdentity(accountToken);
                            // раскодируем ксоря с ID в ASCII
                            ID = win.User.ToString();
                            byte[] tocodekey = Encoding.ASCII.GetBytes(ID);
                            int    q         = 0;
                            for (int i = 0; i < serkey.Length; i++)
                            {
                                if (q == tocodekey.Length)
                                {
                                    q = 0;
                                }
                                serkey[i] = (byte)(serkey[i] ^ tocodekey[q]);
                            }
                            // создём вспомогательный файл для десериализации и извдечение полей класса
                            string help;
                            if (Directory.Exists($"C:/Users/{Environment.UserName}/AppData/Roaming"))
                            {
                                help = $"C:/Users/{Environment.UserName}/AppData/Roaming/Palon/PakmanD{num}Help.txt";
                            }
                            else
                            {
                                help = $"../PakmanD{num}Help.txt";
                            }
                            // так быстрее так как в memorystream нет writeallbytes
                            File.Create(help).Close();
                            File.WriteAllBytes(help, serkey);
                            FileStream l = new FileStream(help, FileMode.Open);
                            cod = (ToCode)json.ReadObject(l);
                            l.Close();
                            // удаляем вспомогательный файл
                            File.Delete(help);
                            // проверяем совпадение устройста
                            devicename   = cod.DeviceName;
                            deviceadress = cod.DeviceAdress;
                            // если устройства нет рядом просим ввести пароль
                            NotFoundCheckingPassword password = new NotFoundCheckingPassword(cod);
                            password.ShowDialog();
                            // проверка верности пароля
                            if (password.Pasbool)
                            {
                                Redeem();
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Two programms are trying to encript file");
                            this.Close();
                        }
                    }
                    else
                    {
                        MessageBox.Show("Two programms are trying to encript file");
                        this.Close();
                    }
                }
            }
        }
Beispiel #2
0
 // метод кодирования
 public void proove()
 {
     Encryptback.Enabled = false;
     // файл
     if (directory)
     {
         try
         {
             // прочитали
             byte[] bytearr2 = File.ReadAllBytes(path);
             File.Delete(path);
             // перевели в base64
             string Inbaseforencrypt = Convert.ToBase64String(bytearr2);
             // зашифровали
             byte[] tofile = EncryptAES(Inbaseforencrypt, key, IV);
             // засереализовали
             Connectwithakey            main = new Connectwithakey(tofile, Encoding.ASCII.GetBytes(num.ToString()));
             DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(Connectwithakey));
             FileStream file = new FileStream(path, FileMode.OpenOrCreate);
             json.WriteObject(file, main);
             file.Close();
             bool   filename  = true;
             int    number    = 2;
             string pathcheck = path;
             // подбираем файл таким образом чтобы не было повтора
             pathcheck = Path.ChangeExtension(pathcheck, ".code3");
             if (File.Exists(pathcheck))
             {
                 while (filename)
                 {
                     pathcheck = Path.ChangeExtension(pathcheck, "");
                     pathcheck = pathcheck.Remove(pathcheck.Length - 1);
                     pathcheck = $"{pathcheck}{number}";
                     pathcheck = $"{pathcheck}.txt";
                     pathcheck = Path.ChangeExtension(pathcheck, ".code3");
                     if (!File.Exists(pathcheck))
                     {
                         filename = false;
                     }
                 }
             }
             File.Move(path, pathcheck);
         }
         catch (Exception)
         {
             MessageBox.Show("One file trying to be decrypted in same time");
             this.Close();
         }
     }
     // папка
     else
     {
         try
         {
             // архивируем (подбираем свободный путь)
             string direct  = Path.ChangeExtension(path, cod.Rassh);
             int    number2 = 2;
             bool   exist   = true;
             while (exist)
             {
                 if (!File.Exists(direct))
                 {
                     ZipFile.CreateFromDirectory(path, direct);
                     exist = false;
                 }
                 else
                 {
                     direct = Path.ChangeExtension(direct, $"");
                     direct.Remove(direct.Length - 1);
                     direct = $"direct{number2}";
                     direct = $"direct{number2}.txt";
                     direct = Path.ChangeExtension(direct, cod.Rassh);
                     number2++;
                 }
             }
             // удаляем первоначальную папку
             Directory.Delete(path, true);
             path = direct;
             // вноь считываем
             byte[] bytearr2 = File.ReadAllBytes(path);
             // удаляем заархивироанный файл
             File.Delete(path);
             // зашифровываем
             string                     Inbaseforencrypt = Convert.ToBase64String(bytearr2);
             byte[]                     tofile           = EncryptAES(Inbaseforencrypt, key, IV);
             Connectwithakey            main             = new Connectwithakey(tofile, Encoding.ASCII.GetBytes(num.ToString()));
             DataContractJsonSerializer json             = new DataContractJsonSerializer(typeof(Connectwithakey));
             FileStream                 file             = new FileStream(path, FileMode.OpenOrCreate);
             // запиываем обратно
             json.WriteObject(file, main);
             file.Close();
             // end with main file
             // start with key file
             bool   filename  = true;
             int    number    = 2;
             string pathcheck = direct;
             // подбираем файл таким образом чтобы не было повтора
             pathcheck = Path.ChangeExtension(pathcheck, ".code4");
             if (File.Exists(pathcheck))
             {
                 while (filename)
                 {
                     pathcheck = Path.ChangeExtension(pathcheck, "");
                     pathcheck = pathcheck.Remove(pathcheck.Length - 1);
                     pathcheck = $"{pathcheck}{number}";
                     pathcheck = Path.ChangeExtension(pathcheck, ".code4");
                     if (!File.Exists(pathcheck))
                     {
                         filename = false;
                     }
                 }
             }
             File.Move(direct, pathcheck);
             // переводим файл в новое расширение
         }
         catch (Exception ex)
         {
             MessageBox.Show("You've already tried to encrypt one folder");
             this.Close();
         }
     }
 }
Beispiel #3
0
        // кнопка готовности ввода
        private void Ready_Click_1(object sender, EventArgs e)
        {
            // проверка количества символов
            if (textBox1.Text.Length >= 8)
            {
                // проверка совпадения паролей
                if (textBox1.Text == textBox2.Text)
                {
                    // провекра файл или папка
                    if (bo == true)
                    {
                        string pathtodirectory = "";
                        // папка для ключей
                        if (Directory.Exists($"C:/Users/{Environment.UserName}/AppData/Roaming"))
                        {
                            pathtodirectory = $"C:/Users/{Environment.UserName}/AppData/Roaming/Palon";
                        }
                        else
                        {
                            pathtodirectory = $"../Palon";
                        }
                        // переменная для остановки подбора
                        bool b = true;
                        // подбор свободного номера для файла
                        int n = -1;
                        while (b)
                        {
                            n++;
                            if (!File.Exists($"{pathtodirectory}/Pakman{n}.txt"))
                            {
                                try
                                {
                                    //создаём папку для ключей
                                    Directory.CreateDirectory(pathtodirectory);
                                    // файл ключа
                                    File.Create($"{pathtodirectory}/Pakman{n}.txt").Close();
                                    // содержимое начального файла
                                    byte[] bytearr2 = File.ReadAllBytes(path);
                                    File.Delete(path);
                                    // генератор рандома
                                    Random gen = new Random();
                                    // генерация ключа
                                    byte[] key = new byte[32];
                                    for (int i = 0; i < key.Length; i++)
                                    {
                                        key[i] = (byte)gen.Next(0, 257);
                                    }
                                    // генерация IV
                                    byte[] IV = new byte[16];
                                    for (int i = 0; i < IV.Length; i++)
                                    {
                                        IV[i] = (byte)gen.Next(0, 255);
                                    }
                                    // переводим ключ в байтовый формат (чтобы можно было сериализовать и хранить более 256 ключей)
                                    byte[] keynumber = Encoding.ASCII.GetBytes(n.ToString());
                                    // Алгоритм кодировки AES
                                    // переводим в base64
                                    string Inbaseforencrypt = Convert.ToBase64String(bytearr2);
                                    // закодрованный массив байтов
                                    byte [] tofile = EncryptAES(Inbaseforencrypt, key, IV);
                                    // объединяем номер файла с основной информцией и сериализуем
                                    Connectwithakey connect = new Connectwithakey(tofile, keynumber);
                                    // записываем в старый путь

                                    FileStream str = new FileStream(path, FileMode.OpenOrCreate);
                                    DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Connectwithakey));
                                    js.WriteObject(str, connect);
                                    str.Close();
                                    // берём пароль
                                    string pass = textBox1.Text;
                                    // для кодирования берется айди безопасности учетно записи, чтобы нельзя было открыть с другого компа
                                    IntPtr          accountToken = WindowsIdentity.GetCurrent().Token;
                                    WindowsIdentity win          = new WindowsIdentity(accountToken);
                                    string          ID           = win.User.ToString();
                                    // ключ ксорится с win
                                    byte[] onlykey = Encoding.UTF8.GetBytes(ID);
                                    int    q       = 0;
                                    for (int i = 0; i < key.Length; i++)
                                    {
                                        if (q == onlykey.Length)
                                        {
                                            q = 0;
                                        }
                                        key[i] = (byte)(key[i] ^ onlykey[q]);
                                    }
                                    // сериализация всех данных безопасности
                                    ToCode serfile = new ToCode(key, IV, Name2, adress, pass, Path.GetExtension(path));
                                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ToCode));
                                    // путь к ключу
                                    string     pathforkey = $"{pathtodirectory}/Pakman{n}.txt";
                                    FileStream fileStream = new FileStream(pathforkey, FileMode.Open);
                                    // сериализуем и записываем ключ
                                    serializer.WriteObject(fileStream, serfile);
                                    fileStream.Close();
                                    // вновь читаем чтобы всё вместе закодировать
                                    byte[] serkey = File.ReadAllBytes(pathforkey);
                                    // ксорим всё вместе с ID в кодировке ASCII
                                    byte[] tocodekey = Encoding.ASCII.GetBytes(ID);
                                    q = 0;
                                    for (int i = 0; i < serkey.Length; i++)
                                    {
                                        if (q == tocodekey.Length)
                                        {
                                            q = 0;
                                        }
                                        serkey[i] = (byte)(serkey[i] ^ tocodekey[q]);
                                    }
                                    // записываем обратно  файл
                                    File.WriteAllBytes(pathforkey, serkey);
                                    // останавливаем подбор файло для ключа
                                    b = false;
                                    // меняем расширение файла для сериализации
                                    bool   filename  = true;
                                    int    number    = 2;
                                    string pathcheck = path;
                                    // подбираем файл таким образом чтобы не было повтора
                                    pathcheck = Path.ChangeExtension(pathcheck, ".code3");
                                    if (File.Exists(pathcheck))
                                    {
                                        while (filename)
                                        {
                                            pathcheck = Path.ChangeExtension(pathcheck, "");
                                            pathcheck = pathcheck.Remove(pathcheck.Length - 1);
                                            pathcheck = $"{pathcheck}{number}";
                                            pathcheck = Path.ChangeExtension(pathcheck, ".code3");
                                            if (!File.Exists(pathcheck))
                                            {
                                                filename = false;
                                            }
                                        }
                                    }
                                    File.Move(path, pathcheck);
                                    this.Close();
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show("Something bad had happened");
                                    this.Close();
                                    b = false;
                                }
                            }
                        }
                    }
                    else
                    {
                        string pathtodirectory = "";
                        // папка для ключей
                        if (Directory.Exists($"C:/Users/{Environment.UserName}/AppData/Roaming"))
                        {
                            pathtodirectory = $"C:/Users/{Environment.UserName}/AppData/Roaming/Palon";
                        }
                        else
                        {
                            pathtodirectory = $"../Palon";
                        }
                        // переменная для подбора свободного ключа
                        bool b = true;
                        // подбор свободного номера для файла
                        int n = -1;
                        while (b)
                        {
                            n++;
                            // проверка существования ключа
                            if (!File.Exists($"{pathtodirectory}/PakmanD{n}.txt"))
                            {
                                try
                                {
                                    // меняем путь
                                    string direct = Path.ChangeExtension(path, "txt");
                                    int    num    = 2;
                                    bool   exist  = true;
                                    // архивируем
                                    while (exist)
                                    {
                                        if (!File.Exists(direct))
                                        {
                                            ZipFile.CreateFromDirectory(path, direct);
                                            exist = false;
                                        }
                                        else
                                        {
                                            direct = Path.ChangeExtension(path, $"txt{num}");
                                            num++;
                                        }
                                    }
                                    Directory.Delete(path, true);
                                    //создаём папку для ключей
                                    Directory.CreateDirectory(pathtodirectory);
                                    // файл ключа
                                    File.Create($"{pathtodirectory}/PakmanD{n}.txt").Close();
                                    // читаем данные архивированной папки
                                    byte[] bytearr2 = File.ReadAllBytes(direct);
                                    // удаляем архивированную папку
                                    File.Delete(direct);
                                    // генератор рандома
                                    Random gen = new Random();
                                    // генерация ключа
                                    byte[] key = new byte[32];
                                    for (int i = 0; i < key.Length; i++)
                                    {
                                        key[i] = (byte)gen.Next(0, 257);
                                    }
                                    // генераия IV
                                    byte[] IV = new byte[16];
                                    for (int i = 0; i < IV.Length; i++)
                                    {
                                        IV[i] = (byte)gen.Next(0, 255);
                                    }
                                    // переводим ключ в байтовый формат (чтобы можно было хранить более 256 ключей)
                                    byte[] keynumber = Encoding.ASCII.GetBytes(n.ToString());
                                    // Алгоритм кодировки AES
                                    // переводим в base64
                                    string Inbaseforencrypt = Convert.ToBase64String(bytearr2);
                                    // энкриптим
                                    byte[] tofile = EncryptAES(Inbaseforencrypt, key, IV);
                                    // объединяем номер файла с основной информцией и сериализуем
                                    Connectwithakey connect = new Connectwithakey(tofile, keynumber);
                                    // записывем получившееся в новый файл
                                    FileStream str = new FileStream(direct, FileMode.OpenOrCreate);
                                    DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Connectwithakey));
                                    js.WriteObject(str, connect);
                                    str.Close();
                                    // пароль
                                    string pass = textBox1.Text;
                                    // для кодирования берется айди безопасности учетно записи, чтобы нельзя было открыть с другого компа
                                    IntPtr          accountToken = WindowsIdentity.GetCurrent().Token;
                                    WindowsIdentity win          = new WindowsIdentity(accountToken);
                                    string          ID           = win.User.ToString();
                                    // ключ ксорится с win
                                    byte[] onlykey = Encoding.UTF8.GetBytes(ID);
                                    int    q       = 0;
                                    for (int i = 0; i < key.Length; i++)
                                    {
                                        if (q == onlykey.Length)
                                        {
                                            q = 0;
                                        }
                                        key[i] = (byte)(key[i] ^ onlykey[q]);
                                    }
                                    // сериализация всех данных безопасности
                                    ToCode serfile = new ToCode(key, IV, Name2, adress, pass, Path.GetExtension(direct));
                                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ToCode));
                                    string     pathforkey = $"{pathtodirectory}/PakmanD{n}.txt";
                                    FileStream fileStream = new FileStream(pathforkey, FileMode.Open);
                                    // записывем в фвйл
                                    serializer.WriteObject(fileStream, serfile);
                                    fileStream.Close();
                                    // вновь читаем для того чтобы всё ксорить с ID в кодировке ASCII
                                    byte[] serkey    = File.ReadAllBytes(pathforkey);
                                    byte[] tocodekey = Encoding.ASCII.GetBytes(ID);
                                    q = 0;
                                    // ксорим
                                    for (int i = 0; i < serkey.Length; i++)
                                    {
                                        if (q == tocodekey.Length)
                                        {
                                            q = 0;
                                        }
                                        serkey[i] = (byte)(serkey[i] ^ tocodekey[q]);
                                    }
                                    // записываем
                                    File.WriteAllBytes(pathforkey, serkey);
                                    // избегаем повтора
                                    b = false;
                                    // меняем расширение файла для сериализации
                                    // проверяем чтобы не было исключений
                                    bool   filename  = true;
                                    int    number    = 2;
                                    string pathcheck = direct;
                                    // подбираем файл таким образом чтобы не было повтора
                                    pathcheck = Path.ChangeExtension(pathcheck, ".code4");
                                    if (File.Exists(pathcheck))
                                    {
                                        while (filename)
                                        {
                                            pathcheck = Path.ChangeExtension(pathcheck, "");
                                            pathcheck = pathcheck.Remove(pathcheck.Length - 1);
                                            pathcheck = $"{pathcheck}{number}";
                                            pathcheck = Path.ChangeExtension(pathcheck, ".code4");
                                            if (!File.Exists(pathcheck))
                                            {
                                                filename = false;
                                            }
                                        }
                                    }
                                    // переводим файл в новое расширение
                                    File.Move(direct, pathcheck);
                                    this.Close();
                                }
                                catch
                                {
                                    MessageBox.Show("Two files");
                                    this.Close();
                                    b = false;
                                }
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Passwords do not match");
                }
            }
            else
            {
                MessageBox.Show("The password must be at least eight characters");
            }
        }