public static void SaveUser(String NameUser, String Password) { if (NameUser.Trim() == "") { MessageOneButton Dialog = new MessageOneButton(); Dialog.Message_L.Text = "Поле логина должно содержать значение"; if (Dialog.ShowDialog() == DialogResult.OK) { } SystemArgs.PrintLog($"Получена пустое значение логина"); return; } if (Password.Trim() == "") { MessageOneButton Dialog = new MessageOneButton(); Dialog.Message_L.Text = "Поле пароля должно содержать значение"; if (Dialog.ShowDialog() == DialogResult.OK) { } SystemArgs.PrintLog($"Получена пустое значение пароля"); return; } if (!Directory.Exists($@"{SystemPath.DataReg}\{NameUser}")) { Directory.CreateDirectory($@"{SystemPath.DataReg}\{NameUser}"); Directory.CreateDirectory($@"{SystemPath.DataUSers}\{NameUser}"); using (StreamWriter sw = new StreamWriter(File.Create($@"{SystemPath.DataReg}\{NameUser}\{NameUser}.hba"))) { sw.WriteLine(NameUser); sw.WriteLine(Password); } SystemArgs.PrintLog($"Директория пользователя {SystemArgs.CurrentUser} создана"); } else { MessageOneButton Dialog = new MessageOneButton(); Dialog.Message_L.Text = "Пользователь с таким именем уже существует. Вы вернетесь к форме авторизации"; if (Dialog.ShowDialog() == DialogResult.OK) { } SystemArgs.PrintLog($"Пользователь существует"); return; } }
public static String DecryptRSA(String OutputPassword, String Password) { if (String.IsNullOrEmpty(OutputPassword)) { MessageOneButton Dialog = new MessageOneButton(); Dialog.Message_L.Text = "Входная строка имела пустое значение"; if (Dialog.ShowDialog() == DialogResult.OK) { } SystemArgs.PrintLog($"Получено пустое значение пароля"); return(null); } ; byte[] VectorB = Encoding.ASCII.GetBytes(Vector); byte[] SaltB = Encoding.ASCII.GetBytes(Salt); byte[] OutputPasswordB = Convert.FromBase64String(OutputPassword); PasswordDeriveBytes DerivePassword = new PasswordDeriveBytes(Password, SaltB, "SHA1", PasswordIter); byte[] KeyBytes = DerivePassword.GetBytes(KeySize / 8); RijndaelManaged SymmKey = new RijndaelManaged(); SymmKey.Mode = CipherMode.CBC; byte[] InitialTextBytes = new byte[OutputPasswordB.Length]; Int32 ByteCount = 0; using (ICryptoTransform Decryptor = SymmKey.CreateDecryptor(KeyBytes, VectorB)) { using (MemoryStream MemoryStream = new MemoryStream(OutputPasswordB)) { using (CryptoStream CryptoStream = new CryptoStream(MemoryStream, Decryptor, CryptoStreamMode.Read)) { ByteCount = CryptoStream.Read(InitialTextBytes, 0, InitialTextBytes.Length); MemoryStream.Close(); CryptoStream.Close(); } } } SymmKey.Clear(); SystemArgs.PrintLog($"Дешифрование пароля завершено успешно"); return(Encoding.UTF8.GetString(InitialTextBytes, 0, ByteCount)); }
private void Reg_Form_FormClosing(object sender, FormClosingEventArgs e) { if (DialogResult == DialogResult.OK) { String error = ""; try { if (Login_TB.Text.Trim() == "") { Login_TB.Focus(); error = "Необходимо ввести логин пользователя"; throw new Exception(error); } if (Pass_TB.Text.Trim() == "") { Pass_TB.Focus(); error = "Необходимо ввеситм пароль пользователя"; throw new Exception(error); } if (Directory.Exists($@"{SystemPath.DataReg}\{Login_TB.Text.Trim()}")) { error = "Пользовтель с таким именем уже существует"; throw new Exception(error); } MessageOneButton Dialog2 = new MessageOneButton(); Dialog2.Message_L.Text = "Пользователь успешно зарегистрирован"; if (Dialog2.ShowDialog() == DialogResult.OK) { } SystemArgs.PrintLog($"Пользователь успешно зарегистрирован"); } catch { MessageOneButton Dialog = new MessageOneButton(); Dialog.Message_L.Text = error; if (Dialog.ShowDialog() == DialogResult.OK) { } e.Cancel = true; } } }
public static String EncryptRSA(String InputPassword, String Password) { if (String.IsNullOrEmpty(InputPassword)) { MessageOneButton Dialog = new MessageOneButton(); Dialog.Message_L.Text = "Входная строка имела пустое значение"; if (Dialog.ShowDialog() == DialogResult.OK) { } SystemArgs.PrintLog($"Получено пустое значение пароля"); return(null); } byte[] VectorB = Encoding.ASCII.GetBytes(Vector); byte[] SaltB = Encoding.ASCII.GetBytes(Salt); byte[] InputPasswordB = Encoding.UTF8.GetBytes(InputPassword); PasswordDeriveBytes DerivePassword = new PasswordDeriveBytes(Password, SaltB, "SHA1", PasswordIter); byte[] KeyBytes = DerivePassword.GetBytes(KeySize / 8); RijndaelManaged SymmKey = new RijndaelManaged(); SymmKey.Mode = CipherMode.CBC; byte[] EncryptrTextBytes = null; using (ICryptoTransform Encryptor = SymmKey.CreateEncryptor(KeyBytes, VectorB)) { using (MemoryStream MemoryStream = new MemoryStream()) { using (CryptoStream CryptoStream = new CryptoStream(MemoryStream, Encryptor, CryptoStreamMode.Write)) { CryptoStream.Write(InputPasswordB, 0, InputPasswordB.Length); CryptoStream.FlushFinalBlock(); EncryptrTextBytes = MemoryStream.ToArray(); MemoryStream.Close(); CryptoStream.Close(); } } } SymmKey.Clear(); SystemArgs.PrintLog($"Шифрование пароля завершено успешно"); return(Convert.ToBase64String(EncryptrTextBytes)); }
private void PositionForm_FormClosing(object sender, FormClosingEventArgs e) { if (DialogResult == DialogResult.OK) { String error = String.Empty; try { if (Name_TB.Text.Trim() == String.Empty) { Name_TB.Focus(); error = "Необходимо ввести наименование позиции"; throw new Exception(error); } if (Pass_TB.Text.Trim() == String.Empty) { Pass_TB.Focus(); error = "Необходимо ввеситм пароль позиции"; throw new Exception(error); } if (Name_TB.Text.Trim().IndexOf("_") != -1) { Name_TB.Focus(); error = "Символ '_' не допустим"; throw new Exception(error); } if (Pass_TB.Text.Trim().IndexOf("_") != -1) { Pass_TB.Focus(); error = "Символ '_' не допустим"; throw new Exception(error); } } catch { MessageOneButton Dialog = new MessageOneButton(); Dialog.Message_L.Text = error; if (Dialog.ShowDialog() == DialogResult.OK) { } e.Cancel = true; } } }
private void ChangeData() { SystemArgs.PrintLog($"Инициализация процедуры изменения позиции"); PositionForm Dialog = new PositionForm { BackgroundImage = Properties.Resources.PositionChange }; DataFile.CurrentDateFile = DateTime.Now; Position LastPosition = SystemArgs.Positions[Positions_DGV.CurrentCell.RowIndex]; Dialog.CurrentDate_TB.Text = LastPosition.DateCreate.ToString(); Dialog.Name_TB.Text = LastPosition.Name; Dialog.Pass_TB.Text = LastPosition.Password; Dialog.Description_TB.Text = LastPosition.Description; if (Dialog.ShowDialog() == DialogResult.OK) { Position Temp = new Position(DataFile.CurrentDateFile, Dialog.Name_TB.Text.Trim(), Dialog.Pass_TB.Text.Trim(), Dialog.Description_TB.Text.Trim()); DataFile.ChangePosition(Temp.DateCreate, Temp.Name, Temp.Password, Temp.Description, LastPosition.DateCreate, LastPosition.Name, Encryption.GetKeyEncryption()); SystemArgs.Positions.Remove(LastPosition); SystemArgs.Positions.Add(Temp); MessageOneButton Dialog2 = new MessageOneButton(); Dialog2.Message_L.Text = "Позиция успешно изменена. Дата создания обновлена"; if (Dialog2.ShowDialog() == DialogResult.OK) { } ShowCurrentPositions(SystemArgs.Positions); SystemArgs.PrintLog($"Изменение позиции успешно завершено"); } else { SystemArgs.PrintLog($"Процедура изменении позиции отменена"); } }
private void Main_Form_Load(object sender, EventArgs e) { Change_B.Enabled = false; Delete_B.Enabled = false; SystemArgs.Positions = new List <Position>(); String[] TempPositions = Operations.GetAllPositions(); FirstRowDGV(); for (Int32 i = 0; i < TempPositions.Length; i++) { Position Temp = Operations.ToPosition(TempPositions[i]); if (Temp == null) { MessageOneButton Dialog = new MessageOneButton(); Dialog.Message_L.Text = "Ошибка при получени данных. Выход из приложения"; if (Dialog.ShowDialog() == DialogResult.OK) { SystemArgs.PrintLog($"Ошибка при получени данных"); } SystemArgs.MainForm.Close(); this.WindowState = FormWindowState.Minimized; // - морграние } else { SystemArgs.Positions.Add(Temp); } } SystemArgs.PrintLog($"Конвертация позиций => Успешно "); ShowCurrentPositions(SystemArgs.Positions); SystemArgs.PrintLog($"Визуализация позиций => Успешно "); //Positions_DGV.ClearSelection(); //Убираем выделение первой ячейки при загрузке таблицы }
public static String [] GetAllPositions() { SystemArgs.PrintLog($"Процедура получения позиций пользователя => Старт "); String Data = ""; String[] PathFiles; if (Directory.Exists($@"{SystemPath.DataUSers}\{SystemArgs.CurrentUser.Name}")) { PathFiles = Directory.GetFiles($@"{SystemPath.DataUSers}\{SystemArgs.CurrentUser.Name}"); for (Int32 i = 0; i < PathFiles.Length; i++) { using (StreamReader sr = new StreamReader(File.Open(PathFiles[i], FileMode.Open))) { Data = sr.ReadLine(); } PathFiles[i] = Data; } } else { MessageOneButton Dialog = new MessageOneButton(); Dialog.Message_L.Text = "Директория пользователя не найдена"; if (Dialog.ShowDialog() == DialogResult.OK) { } SystemArgs.PrintLog($"Директория пользователя не найдена"); return(new String[0]); } return(PathFiles); }
private void Search_B_Click(object sender, EventArgs e) { String Search = Search_TB.Text.Trim(); if (Search == String.Empty) { ResetSearch(); return; } SystemArgs.Result.Clear(); foreach (Position Temp in SystemArgs.Positions) { if (Temp.GetSearchString().IndexOf(Search) != -1) { SystemArgs.Result.Add(Temp); } } if (SystemArgs.Result.Count != 0) { ShowCurrentPositions(SystemArgs.Result); SystemArgs.PrintLog($"Удачное завершение поиска поиска. Результатов {SystemArgs.Result.Count}"); } else { MessageOneButton Dialog = new MessageOneButton(); Dialog.Message_L.Text = "Поиск не дал результатов"; if (Dialog.ShowDialog() == DialogResult.OK) { SystemArgs.PrintLog($"Поиск не дал результатов"); return; } } }
public static void ByName(bool OrderBy) { List <Position> TempList = SystemArgs.Positions; //Копируем элементы для сохранения try { if (OrderBy) { var SortedData = from p in TempList orderby p.Name ascending select p; SystemArgs.Positions = SortedData.ToList(); } else { var SortedData = from p in TempList orderby p.Name descending select p; SystemArgs.Positions = SortedData.ToList(); } } catch (Exception) { MessageOneButton Dialog = new MessageOneButton(); Dialog.Message_L.Text = "Ошибка при сортировке. Данные будут восстановлены"; if (Dialog.ShowDialog() == DialogResult.OK) { } SystemArgs.Positions = TempList; //Возращаем объекты в исходное состояние return; } }
private void Add_B_Click(object sender, EventArgs e) { SystemArgs.PrintLog($"Инициализация процедуры добавления позиции"); PositionForm Dialog = new PositionForm { BackgroundImage = Properties.Resources.Position }; DataFile.CurrentDateFile = DateTime.Now; Dialog.CurrentDate_TB.Text = DataFile.CurrentDateFile.ToString(); if (Dialog.ShowDialog() == DialogResult.OK) { Position Temp = new Position(DataFile.CurrentDateFile, Dialog.Name_TB.Text.Trim(), Dialog.Pass_TB.Text.Trim(), Dialog.Description_TB.Text.Trim()); SystemArgs.Positions.Add(Temp); DataFile.SetPosition(Temp.DateCreate, Temp.Name, Temp.Password, Temp.Description, Encryption.GetKeyEncryption()); MessageOneButton Dialog2 = new MessageOneButton(); Dialog2.Message_L.Text = "Позиция успешно добавлена"; if (Dialog2.ShowDialog() == DialogResult.OK) { } ShowCurrentPositions(SystemArgs.Positions); SystemArgs.PrintLog($"Добавление позиции завершено успешно"); } else { SystemArgs.PrintLog($"Процедура добавления позиции отменена"); } }
public static void GetDataLogPath() { if (File.Exists(DataLogPath)) { using (StreamReader sr = new StreamReader(File.Open(DataLogPath, FileMode.Open))) { DataLog = sr.ReadLine(); } } else { MessageOneButton Dialog = new MessageOneButton(); Dialog.Message_L.Text = "Файл DateLog.conf не обнаружен"; if (Dialog.ShowDialog() == DialogResult.OK) { } SystemArgs.PrintLog($"Файл DataLog.conf не найден"); return; } }
public static bool GetUserStatus(String Login, String Pass) { if (File.Exists($@"{SystemPath.DataReg}\{Login}\{Login}.hba")) { using (StreamReader sr = new StreamReader(File.Open($@"{SystemPath.DataReg}\{Login}\{Login}.hba", FileMode.Open))) { String TempLogin = sr.ReadLine(); String TempPass = sr.ReadLine(); if (TempLogin == Login) { if (TempPass == Pass) { return(true); } else { MessageOneButton Dialog = new MessageOneButton(); Dialog.Message_L.Text = $@"Неправильный логин или пароль"; if (Dialog.ShowDialog() == DialogResult.OK) { } SystemArgs.PrintLog($"Получен неправильный логин или пароль"); return(false); } } else { MessageOneButton Dialog = new MessageOneButton(); Dialog.Message_L.Text = $@"Неправильный логин или пароль"; if (Dialog.ShowDialog() == DialogResult.OK) { } SystemArgs.PrintLog($"Получен неправильный логин или пароль"); return(false); } } } else { MessageOneButton Dialog = new MessageOneButton(); Dialog.Message_L.Text = $@"Файл {Login}.hba не обнаружен"; if (Dialog.ShowDialog() == DialogResult.OK) { } SystemArgs.PrintLog($"Конфигурационный файл {Login}.hba не найден"); return(false); } }
private void Enter_B_Click(object sender, EventArgs e) { String CurrentLogin = Login_TB.Text.Trim(); if (CurrentLogin != "") { if (Autorization.GetUserExists(CurrentLogin)) { String CurrentPass = Pass_TB.Text.Trim(); if (CurrentPass != "") { if (Autorization.GetUserStatus(CurrentLogin, Hash.GetSHA256(CurrentPass))) { SystemArgs.CurrentUser = new User(CurrentLogin); SystemArgs.PrintLog($"Пользователь {SystemArgs.CurrentUser.Name} успешно авторизовался"); Main_Form Main = new Main_Form(); Main.Show(); this.Hide(); } } else { MessageOneButton Dialog = new MessageOneButton(); Dialog.Message_L.Text = "Поле пароля должно содержать значение"; if (Dialog.ShowDialog() == DialogResult.OK) { } SystemArgs.PrintLog($"Получено пустое поле пароля"); Pass_TB.Focus(); return; } } else { MessageOneButton Dialog = new MessageOneButton(); Dialog.Message_L.Text = $@"Неправильный логин или пароль"; if (Dialog.ShowDialog() == DialogResult.OK) { } SystemArgs.PrintLog($"Введен енправильный логин или пароль"); } } else { MessageOneButton Dialog = new MessageOneButton(); Dialog.Message_L.Text = "Поле логина должно содержать значение"; if (Dialog.ShowDialog() == DialogResult.OK) { } SystemArgs.PrintLog($"Получено пустое поле логина"); Login_TB.Focus(); return; } }
public static void CheckFiles() { try { SystemArgs.PrintLog($"Запуск приложения"); if (!File.Exists(SystemPath.DataRegPath)) { throw new Exception(); } if (!File.Exists(SystemPath.DataUSersPath)) { throw new Exception(); } if (!File.Exists(SystemPath.DataLogPath)) { throw new Exception(); } SystemPath.GetDataRegPath(); SystemPath.GetDataLogPath(); SystemPath.GetDataUsersPath(); if (!Directory.Exists(SystemPath.DataLog)) { throw new Exception(); } if (!Directory.Exists(SystemPath.DataReg)) { throw new Exception(); } if (!Directory.Exists(SystemPath.DataUSers)) { throw new Exception(); } } catch (UnauthorizedAccessException) { MessageOneButton Dialog = new MessageOneButton(); Dialog.Message_L.Text = "Недостаточно прав для доступа к системным файлам"; if (Dialog.ShowDialog() == DialogResult.OK) { } SystemArgs.PrintLog($"Недостаточно прав доступа для запуска ПО"); Environment.Exit(0); //Завершение процесса } catch (Exception) { MessageOneButton Dialog = new MessageOneButton(); Dialog.Message_L.Text = "Ошибка при получении путей конфигурации"; if (Dialog.ShowDialog() == DialogResult.OK) { } SystemArgs.PrintLog($"Файл конфигурации не найден"); Environment.Exit(0); //Завершение процесса } }