Advertisement
Shokedbrain

lab4_cryptoapi

Apr 29th, 2022
1,764
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <fstream>
  2. #include <Windows.h>
  3. #include <wincrypt.h>
  4. #include <iostream>
  5.  
  6. using namespace std;
  7.  
  8.  
  9. void ErrorHandling() {
  10.     DWORD dw = GetLastError();
  11.     cout << "Error: " << hex << dw << endl;
  12. }
  13.  
  14. // принимает 4 аргумента: данные для шифрования, пароль, переменная для хранения результата
  15. // и режим шифрования(true)/дешифрования(false)
  16. int symmetricOperate(const string &data, const string password, string &result, bool mode)
  17. {
  18.     if (data.length() == 0 || password.length() == 0)
  19.     {
  20.         // проверка входных данных на корректность
  21.         cout << "Input data or password is wrong. Please, try again.\n";
  22.         return -1;
  23.     }
  24.     result = data;
  25.     HCRYPTPROV      hProv; // дескриптор криптопровайдера
  26.     HCRYPTHASH      hHash; // дескриптор хеша
  27.     HCRYPTKEY       hKey;  // дескриптор криптографического ключа
  28.     DWORD           dataLength = static_cast<DWORD>(data.length()); // длина входной строки
  29.  
  30.     cout << "\tInput data\n";
  31.     cout << "Data: " << data << endl;
  32.     cout << "Data length: " << data.length() << endl;
  33.     //  CryptAcquireContext получает дескриптор используемого в данный момент ключевого контейнера, находящегося в определенном CSP.
  34.  
  35.     if (!CryptAcquireContext(&hProv, nullptr, MS_DEF_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
  36.     {
  37.         ErrorHandling();
  38.         return -1;
  39.     }
  40.     // хешируем данные для дальнейшей передачи в CryptDeriveKey
  41.     if (!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash))
  42.     {
  43.         ErrorHandling();
  44.         CryptReleaseContext(hProv, 0);
  45.         return -1;
  46.     }
  47.     if (!CryptHashData(hHash, (BYTE*)password.c_str(), password.length(), 0))
  48.     {
  49.         ErrorHandling();
  50.         CryptDestroyHash(hHash);
  51.         return -1;
  52.     }
  53.     // Функция CryptDeriveKey генерит криптографические сессионные ключи, получая их из исходных данных
  54.     // Функция CryptDeriveKey создает ключ, получая его из пароля.
  55.     if (!CryptDeriveKey(hProv, CALG_RC4, hHash, 0, &hKey))
  56.     {
  57.         ErrorHandling();
  58.         CryptDestroyHash(hHash);
  59.     }
  60.     if (mode)
  61.     {
  62.         cout << "\tEncryption\n";
  63.         // шифруем данные
  64.         if (CryptEncrypt(hKey, 0, TRUE, 0, (BYTE*)result.c_str(), &dataLength, data.length()))
  65.         {
  66.             cout << "Encrypted successfully\n";
  67.             cout << "Encrypted string: " << result << endl;
  68.             cout << "Encrypted data length:" << static_cast<int>(dataLength) << endl;
  69.         }
  70.         else
  71.         {
  72.             ErrorHandling();
  73.             CryptDestroyKey(hKey);
  74.         }
  75.     }
  76.     else
  77.     {
  78.         cout << "\tDecryption\n";
  79.         if (CryptDecrypt(hKey, 0, TRUE, 0, (BYTE*)result.c_str(), &dataLength))
  80.         {
  81.             cout << "Decrypted successfully\n";
  82.             cout << "Decrypted string: " << result << endl;
  83.             cout << "Decrypted data length: " << static_cast<int>(dataLength) << endl;
  84.         }
  85.         else
  86.         {
  87.             ErrorHandling();
  88.             CryptDestroyKey(hKey);
  89.         }
  90.     }
  91.     return 0;
  92. }
  93.  
  94.  
  95.  
  96. int main()
  97. {
  98.     string dir{};
  99.     cout << "enter dir: ";
  100.     cin >> dir;
  101.     ifstream in(dir);
  102.     if (!in.good())
  103.     {
  104.         cout << "error dir!\n";
  105.         return -1;
  106.     }
  107.     // read contents from file
  108.     string content{istreambuf_iterator<char>(in),
  109.         istreambuf_iterator<char>()};
  110.     cout << content << endl;
  111.     // set password
  112.     string password = "#@$4&";
  113.  
  114.     string res{};
  115.     symmetricOperate(content, password, res, true);
  116.     cout << res << endl;
  117.     string encrypted = res;
  118.     res = "";
  119.     symmetricOperate(encrypted, password, res, false);
  120.     cout << res << endl;
  121.     system("pause");
  122.     return 0;
  123. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement