Загрузка данных
#pragma once
#include <Windows.h>
#include <fstream>
#include <string>
#include <msclr/marshal_cppstd.h>
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace msclr::interop;
namespace PasswordProtection {
// Класс для шифрования/дешифрования
public ref class CryptoHelper {
public:
// Простое XOR шифрование
static System::String^ EncryptDecrypt(System::String^ input, int key) {
array<wchar_t>^ chars = input->ToCharArray();
for (int i = 0; i < chars->Length; i++) {
chars[i] = chars[i] ^ key;
}
return gcnew System::String(chars);
}
};
// Форма ввода пароля
public ref class LoginForm : public System::Windows::Forms::Form {
private:
System::Windows::Forms::TextBox^ txtPassword;
System::Windows::Forms::Button^ btnLogin;
System::Windows::Forms::Label^ lblMessage;
System::Windows::Forms::Label^ lblTitle;
int attemptsLeft;
System::String^ correctPassword;
public:
LoginForm() {
attemptsLeft = 3;
LoadPasswordFromFile();
InitializeComponent();
}
protected:
~LoginForm() {
if (components) {
delete components;
}
}
private:
void InitializeComponent() {
this->txtPassword = gcnew System::Windows::Forms::TextBox();
this->btnLogin = gcnew System::Windows::Forms::Button();
this->lblMessage = gcnew System::Windows::Forms::Label();
this->lblTitle = gcnew System::Windows::Forms::Label();
this->SuspendLayout();
// lblTitle
this->lblTitle->AutoSize = true;
this->lblTitle->Font = gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14, FontStyle::Bold);
this->lblTitle->Location = System::Drawing::Point(80, 20);
this->lblTitle->Size = System::Drawing::Size(200, 24);
this->lblTitle->Text = L"Введите пароль";
// txtPassword
this->txtPassword->Location = System::Drawing::Point(50, 60);
this->txtPassword->Size = System::Drawing::Size(200, 22);
this->txtPassword->PasswordChar = '*';
this->txtPassword->UseSystemPasswordChar = false;
// btnLogin
this->btnLogin->Location = System::Drawing::Point(110, 100);
this->btnLogin->Size = System::Drawing::Size(75, 30);
this->btnLogin->Text = L"Вход";
this->btnLogin->UseVisualStyleBackColor = true;
this->btnLogin->Click += gcnew System::EventHandler(this, &LoginForm::btnLogin_Click);
// lblMessage
this->lblMessage->AutoSize = true;
this->lblMessage->Font = gcnew System::Drawing::Font(L"Microsoft Sans Serif", 9);
this->lblMessage->Location = System::Drawing::Point(50, 140);
this->lblMessage->Size = System::Drawing::Size(200, 20);
this->lblMessage->Text = String::Format(L"Осталось попыток: {0}", attemptsLeft);
// LoginForm
this->AutoScaleDimensions = System::Drawing::SizeF(8, 16);
this->AutoScaleMode = AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(300, 180);
this->Controls->Add(this->lblMessage);
this->Controls->Add(this->btnLogin);
this->Controls->Add(this->txtPassword);
this->Controls->Add(this->lblTitle);
this->StartPosition = FormStartPosition::CenterScreen;
this->Text = L"Парольная защита";
this->FormClosing += gcnew System::Windows::Forms::FormClosingEventHandler(this, &LoginForm::LoginForm_FormClosing);
this->ResumeLayout(false);
this->PerformLayout();
}
void LoadPasswordFromFile() {
try {
std::ifstream file("password.dat", std::ios::binary);
if (file.is_open()) {
std::string encryptedPass;
std::getline(file, encryptedPass);
file.close();
// Расшифровываем
System::String^ encrypted = marshal_as<System::String^>(encryptedPass);
correctPassword = CryptoHelper::EncryptDecrypt(encrypted, 123);
} else {
// Если файла нет, создаем пароль по умолчанию "admin"
correctPassword = L"admin";
SavePasswordToFile(correctPassword);
}
} catch(...) {
correctPassword = L"admin";
}
}
void SavePasswordToFile(System::String^ password) {
try {
// Шифруем пароль
System::String^ encrypted = CryptoHelper::EncryptDecrypt(password, 123);
std::string encryptedStr = marshal_as<std::string>(encrypted);
std::ofstream file("password.dat", std::ios::binary);
if (file.is_open()) {
file << encryptedStr;
file.close();
}
} catch(...) {
MessageBox::Show(L"Ошибка сохранения пароля!", L"Ошибка");
}
}
void btnLogin_Click(System::Object^ sender, System::EventArgs^ e) {
if (txtPassword->Text == correctPassword) {
// Пароль правильный - открываем главное окно
this->Hide();
MainForm^ mainForm = gcnew MainForm(this, correctPassword);
mainForm->ShowDialog();
// После закрытия главного окна закрываем приложение
Application::Exit();
} else {
attemptsLeft--;
lblMessage->Text = String::Format(L"Осталось попыток: {0}", attemptsLeft);
if (attemptsLeft <= 0) {
MessageBox::Show(L"Попытки закончились! Программа будет закрыта.",
L"Доступ запрещен", MessageBoxButtons::OK, MessageBoxIcon::Stop);
Application::Exit();
} else {
MessageBox::Show(L"Неверный пароль! Попробуйте снова.",
L"Ошибка", MessageBoxButtons::OK, MessageBoxIcon::Warning);
txtPassword->Clear();
txtPassword->Focus();
}
}
}
void LoginForm_FormClosing(Object^ sender, FormClosingEventArgs^ e) {
Application::Exit();
}
};
// Главное окно (Заставка)
public ref class MainForm : public System::Windows::Forms::Form {
private:
LoginForm^ loginForm;
System::String^ currentPassword;
System::Windows::Forms::Label^ lblWelcome;
System::Windows::Forms::Button^ btnChangePassword;
System::Windows::Forms::Button^ btnExit;
System::Windows::Forms::PictureBox^ pictureBox;
System::Windows::Forms::TextBox^ txtNewPassword;
System::Windows::Forms::TextBox^ txtConfirmPassword;
System::Windows::Forms::Label^ lblNewPass;
System::Windows::Forms::Label^ lblConfirm;
public:
MainForm(LoginForm^ form, System::String^ password) {
loginForm = form;
currentPassword = password;
InitializeComponent();
}
private:
void InitializeComponent() {
this->lblWelcome = gcnew System::Windows::Forms::Label();
this->btnChangePassword = gcnew System::Windows::Forms::Button();
this->btnExit = gcnew System::Windows::Forms::Button();
this->pictureBox = gcnew System::Windows::Forms::PictureBox();
this->txtNewPassword = gcnew System::Windows::Forms::TextBox();
this->txtConfirmPassword = gcnew System::Windows::Forms::TextBox();
this->lblNewPass = gcnew System::Windows::Forms::Label();
this->lblConfirm = gcnew System::Windows::Forms::Label();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox))->BeginInit();
this->SuspendLayout();
// lblWelcome
this->lblWelcome->AutoSize = true;
this->lblWelcome->Font = gcnew System::Drawing::Font(L"Microsoft Sans Serif", 16, FontStyle::Bold);
this->lblWelcome->ForeColor = System::Drawing::Color::Blue;
this->lblWelcome->Location = System::Drawing::Point(120, 30);
this->lblWelcome->Size = System::Drawing::Size(250, 30);
this->lblWelcome->Text = L"ДОБРО ПОЖАЛОВАТЬ!";
// pictureBox
this->pictureBox->BackColor = System::Drawing::Color::LightBlue;
this->pictureBox->Location = System::Drawing::Point(80, 80);
this->pictureBox->Size = System::Drawing::Size(300, 100);
this->pictureBox->BorderStyle = BorderStyle::FixedSingle;
// lblNewPass
this->lblNewPass->AutoSize = true;
this->lblNewPass->Location = System::Drawing::Point(50, 200);
this->lblNewPass->Text = L"Новый пароль:";
// txtNewPassword
this->txtNewPassword->Location = System::Drawing::Point(180, 197);
this->txtNewPassword->Size = System::Drawing::Size(150, 22);
this->txtNewPassword->PasswordChar = '*';
// lblConfirm
this->lblConfirm->AutoSize = true;
this->lblConfirm->Location = System::Drawing::Point(50, 235);
this->lblConfirm->Text = L"Подтверждение:";
// txtConfirmPassword
this->txtConfirmPassword->Location = System::Drawing::Point(180, 232);
this->txtConfirmPassword->Size = System::Drawing::Size(150, 22);
this->txtConfirmPassword->PasswordChar = '*';
// btnChangePassword
this->btnChangePassword->Location = System::Drawing::Point(100, 280);
this->btnChangePassword->Size = System::Drawing::Size(120, 35);
this->btnChangePassword->Text = L"Сменить пароль";
this->btnChangePassword->UseVisualStyleBackColor = true;
this->btnChangePassword->Click += gcnew System::EventHandler(this, &MainForm::btnChangePassword_Click);
// btnExit
this->btnExit->Location = System::Drawing::Point(240, 280);
this->btnExit->Size = System::Drawing::Size(100, 35);
this->btnExit->Text = L"Выход";
this->btnExit->UseVisualStyleBackColor = true;
this->btnExit->Click += gcnew System::EventHandler(this, &MainForm::btnExit_Click);
// MainForm
this->AutoScaleDimensions = System::Drawing::SizeF(8, 16);
this->AutoScaleMode = AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(450, 350);
this->Controls->Add(this->btnExit);
this->Controls->Add(this->btnChangePassword);
this->Controls->Add(this->txtConfirmPassword);
this->Controls->Add(this->lblConfirm);
this->Controls->Add(this->txtNewPassword);
this->Controls->Add(this->lblNewPass);
this->Controls->Add(this->pictureBox);
this->Controls->Add(this->lblWelcome);
this->StartPosition = FormStartPosition::CenterScreen;
this->Text = L"Заставка программы";
this->BackColor = System::Drawing::Color::LightGray;
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox))->EndInit();
this->ResumeLayout(false);
this->PerformLayout();
}
void SavePassword(System::String^ newPassword) {
try {
// Шифруем пароль
System::String^ encrypted = CryptoHelper::EncryptDecrypt(newPassword, 123);
std::string encryptedStr = marshal_as<std::string>(encrypted);
std::ofstream file("password.dat", std::ios::binary);
if (file.is_open()) {
file << encryptedStr;
file.close();
currentPassword = newPassword;
}
} catch(...) {
MessageBox::Show(L"Ошибка сохранения пароля!", L"Ошибка");
}
}
void btnChangePassword_Click(System::Object^ sender, System::EventArgs^ e) {
System::String^ newPass = txtNewPassword->Text;
System::String^ confirmPass = txtConfirmPassword->Text;
if (newPass->Length < 3) {
MessageBox::Show(L"Пароль должен содержать минимум 3 символа!",
L"Ошибка", MessageBoxButtons::OK, MessageBoxIcon::Warning);
return;
}
if (newPass != confirmPass) {
MessageBox::Show(L"Пароли не совпадают!",
L"Ошибка", MessageBoxButtons::OK, MessageBoxIcon::Warning);
return;
}
SavePassword(newPass);
MessageBox::Show(L"Пароль успешно изменен!",
L"Успех", MessageBoxButtons::OK, MessageBoxIcon::Information);
txtNewPassword->Clear();
txtConfirmPassword->Clear();
}
void btnExit_Click(System::Object^ sender, System::EventArgs^ e) {
Application::Exit();
}
};
}