Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fstream>
- #include <Windows.h>
- #include <wincrypt.h>
- #include <iostream>
- using namespace std;
- void ErrorHandling() {
- DWORD dw = GetLastError();
- cout << "Error: " << hex << dw << endl;
- }
- // принимает 4 аргумента: данные для шифрования, пароль, переменная для хранения результата
- // и режим шифрования(true)/дешифрования(false)
- int symmetricOperate(const string &data, const string password, string &result, bool mode)
- {
- if (data.length() == 0 || password.length() == 0)
- {
- // проверка входных данных на корректность
- cout << "Input data or password is wrong. Please, try again.\n";
- return -1;
- }
- result = data;
- HCRYPTPROV hProv; // дескриптор криптопровайдера
- HCRYPTHASH hHash; // дескриптор хеша
- HCRYPTKEY hKey; // дескриптор криптографического ключа
- DWORD dataLength = static_cast<DWORD>(data.length()); // длина входной строки
- cout << "\tInput data\n";
- cout << "Data: " << data << endl;
- cout << "Data length: " << data.length() << endl;
- // CryptAcquireContext получает дескриптор используемого в данный момент ключевого контейнера, находящегося в определенном CSP.
- if (!CryptAcquireContext(&hProv, nullptr, MS_DEF_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
- {
- ErrorHandling();
- return -1;
- }
- // хешируем данные для дальнейшей передачи в CryptDeriveKey
- if (!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash))
- {
- ErrorHandling();
- CryptReleaseContext(hProv, 0);
- return -1;
- }
- if (!CryptHashData(hHash, (BYTE*)password.c_str(), password.length(), 0))
- {
- ErrorHandling();
- CryptDestroyHash(hHash);
- return -1;
- }
- // Функция CryptDeriveKey генерит криптографические сессионные ключи, получая их из исходных данных
- // Функция CryptDeriveKey создает ключ, получая его из пароля.
- if (!CryptDeriveKey(hProv, CALG_RC4, hHash, 0, &hKey))
- {
- ErrorHandling();
- CryptDestroyHash(hHash);
- }
- if (mode)
- {
- cout << "\tEncryption\n";
- // шифруем данные
- if (CryptEncrypt(hKey, 0, TRUE, 0, (BYTE*)result.c_str(), &dataLength, data.length()))
- {
- cout << "Encrypted successfully\n";
- cout << "Encrypted string: " << result << endl;
- cout << "Encrypted data length:" << static_cast<int>(dataLength) << endl;
- }
- else
- {
- ErrorHandling();
- CryptDestroyKey(hKey);
- }
- }
- else
- {
- cout << "\tDecryption\n";
- if (CryptDecrypt(hKey, 0, TRUE, 0, (BYTE*)result.c_str(), &dataLength))
- {
- cout << "Decrypted successfully\n";
- cout << "Decrypted string: " << result << endl;
- cout << "Decrypted data length: " << static_cast<int>(dataLength) << endl;
- }
- else
- {
- ErrorHandling();
- CryptDestroyKey(hKey);
- }
- }
- return 0;
- }
- int main()
- {
- string dir{};
- cout << "enter dir: ";
- cin >> dir;
- ifstream in(dir);
- if (!in.good())
- {
- cout << "error dir!\n";
- return -1;
- }
- // read contents from file
- string content{istreambuf_iterator<char>(in),
- istreambuf_iterator<char>()};
- cout << content << endl;
- // set password
- string password = "#@$4&";
- string res{};
- symmetricOperate(content, password, res, true);
- cout << res << endl;
- string encrypted = res;
- res = "";
- symmetricOperate(encrypted, password, res, false);
- cout << res << endl;
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement