Guest User

Symmetric and Hybrid E D CryptoApi

a guest
Mar 1st, 2021
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 6.65 KB | None | 0 0
  1. #include <Windows.h>
  2. #include <wincrypt.h>
  3. #include <iostream>
  4.  
  5. using namespace std;
  6.  
  7.  
  8. void ErrorHandling(){
  9.     DWORD dw = GetLastError();
  10.     cout << "Error: " << hex << dw << endl;
  11. }
  12.  
  13. int symmetricED()
  14. {
  15.     // шифрование
  16.     // хеширование
  17.     // cryptderivekey
  18.     // cryptencrypt
  19.     string          password = "#@$4&"; // секретные данные
  20.     string          data = "Hello, World!"; // что мы хотим зашифровать
  21.     if (data.length() == 0)
  22.     {
  23.         // проверка входных данных на корректность
  24.         cout << "Input data is wrong. Please, try again.\n";
  25.         return -1;
  26.     }
  27.     string          encryptedData = data; // куда мы запихнём зашифрованные данные
  28.     HCRYPTPROV      hProv; // дескриптор криптопровайдера
  29.     HCRYPTHASH      hHash; // дескриптор хеша
  30.     HCRYPTKEY       hKey;  // дескриптор криптографического ключа
  31.     DWORD           dataLength = (DWORD)data.length(); // длина входной строки
  32.     cout << "\t\tInput data\n";
  33.     cout << "Data: " << data << endl;
  34.     cout << "Data length: " << data.length() << endl;
  35.     //  CryptAcquireContext получает дескриптор используемого в данный момент ключевого контейнера, находящегося в определенном CSP.
  36.     if (CryptAcquireContext(&hProv,NULL,MS_DEF_PROV,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT))
  37.     {
  38.         // хешируем данные для дальнейшей передачи в CryptDeriveKey
  39.         if (CryptCreateHash(hProv,CALG_MD5,0,0,&hHash))
  40.         {
  41.             if (CryptHashData(hHash,(BYTE*)password.c_str(),password.length(),0))
  42.             {
  43.                 // Функция CryptDeriveKey генерит криптографические сессионные ключи, получая их из исходных данных
  44.                 // Функция CryptDeriveKey создает ключ, получая его из пароля.
  45.                 if (CryptDeriveKey(hProv,CALG_RC4,hHash,0,&hKey))
  46.                 {
  47.                     cout << "\t\t Encryption\n";
  48.                     // шифруем данные
  49.                     if (CryptEncrypt(hKey,0,TRUE,0, (BYTE *)encryptedData.c_str(),&dataLength,data.length()))
  50.                     {
  51.                         cout << "Encrypted successfully\n";
  52.                         cout << "Encrypted string: " << encryptedData << endl;
  53.                         cout << "Encrypted data length:" << static_cast<int>(dataLength) << endl;
  54.                     }
  55.                     else
  56.                     {
  57.                         ErrorHandling();
  58.                         CryptDestroyKey(hKey);
  59.                     }
  60.                     cout << "\t\t Decryption\n";
  61.                     // расшифровываем данные
  62.                     string decryptedData = encryptedData;
  63.                     if (CryptDecrypt(hKey,0,TRUE,0,(BYTE *)decryptedData.c_str(),&dataLength))
  64.                     {
  65.                         cout << "Decrypted successfully\n";
  66.                         cout << "Decrypted string: " << decryptedData << endl;
  67.                         cout << "Decrypted data length: " << static_cast<int>(dataLength) << endl;
  68.                     }
  69.                     else
  70.                     {
  71.                         ErrorHandling();
  72.                         CryptDestroyKey(hKey);
  73.                     }
  74.                 }
  75.                 else
  76.                 {
  77.                     ErrorHandling();
  78.                     CryptDestroyHash(hHash);
  79.                 }
  80.             }
  81.             else
  82.             {
  83.                 ErrorHandling();
  84.                 CryptDestroyHash(hHash);
  85.             }
  86.         }
  87.         else
  88.         {
  89.             ErrorHandling();
  90.             CryptReleaseContext(hProv,0);
  91.             return -1;
  92.         }
  93.     }
  94.     else
  95.     {
  96.         ErrorHandling();
  97.         return -1;
  98.     }
  99.     return 0;
  100. }
  101.  
  102.  
  103. int hybridED(){
  104.     string          data = "Hello, World!"; // входная строка
  105.     string          encryptedData = data;
  106.     DWORD           dataLength = static_cast<DWORD>(data.length()); // её длина
  107.     HCRYPTPROV      hProv;
  108.     LPCWSTR         hName = L"Container"; // имя контейнера
  109.     HCRYPTKEY       hSessionKey, hExportKey; // ключ сессии и публичный
  110.     HCRYPTKEY       hImportKey; // ключ для импорта
  111.     DWORD           pbDataLen = 0; // длина массива для экспорта ключа
  112.     if (!CryptAcquireContext(&hProv,hName,NULL,PROV_RSA_FULL,CRYPT_NEWKEYSET))
  113.     {
  114.         ErrorHandling();
  115.         return -1;
  116.     }
  117.     // генерируем ключ сессии
  118.     cout << "Generating session key\n";
  119.     if (!CryptGenKey(hProv,CALG_RC4,
  120.         CRYPT_EXPORTABLE | CRYPT_ENCRYPT | CRYPT_DECRYPT,
  121.         &hSessionKey))
  122.     {
  123.         ErrorHandling();
  124.         return -1;
  125.     }
  126.     cout << "Session key has been generated\n";
  127.     // генерируем ключ для экспорта в данном контексте
  128.     cout << "Generating export key\n";
  129.     if (!CryptGenKey(hProv,AT_KEYEXCHANGE,0,&hExportKey))
  130.     {
  131.         ErrorHandling();
  132.         return -1;
  133.     }
  134.     if (!CryptGetUserKey(hProv,AT_KEYEXCHANGE,&hExportKey))
  135.     {
  136.         ErrorHandling();
  137.         return -1;
  138.     }
  139.     cout << "Export key has been generated\n";
  140.     // рассчитываем длину для экспорта ключа
  141.     if (!CryptExportKey(hSessionKey,hExportKey,SIMPLEBLOB,0,NULL,&pbDataLen))
  142.     {
  143.         ErrorHandling();
  144.         return -1;
  145.     }
  146.  
  147.     PBYTE exportKey = static_cast<PBYTE>(malloc(pbDataLen));
  148.     ZeroMemory(exportKey,pbDataLen);
  149.     // Экспортируем ключ шифрования
  150.     if (!CryptExportKey(hSessionKey,hExportKey,SIMPLEBLOB,0, exportKey,&pbDataLen))
  151.     {
  152.         ErrorHandling();
  153.         return -1;
  154.     }
  155.     cout << "Key has been exported\n";
  156.  
  157.     cout << "Data encryption\n";
  158.     cout << "\t\tInput data\n";
  159.     cout << "Data: " << data << endl;
  160.     cout << "Data length: " << data.length() << endl;
  161.     if (!CryptEncrypt(hSessionKey,0,TRUE,0,
  162.         (PBYTE) encryptedData.c_str(),&dataLength,data.length()))
  163.     {
  164.         ErrorHandling();
  165.         return -1;
  166.     }
  167.     else
  168.     {
  169.         cout << "Encrypted successfully\n";
  170.         cout << "Encrypted string: " << encryptedData << endl;
  171.         cout << "Encrypted data length:" << static_cast<int>(dataLength) << endl;
  172.     }
  173.    
  174.     cout << "Data decryption\n";
  175.  
  176.     cout << "Importing key\n";
  177.     if (!CryptImportKey(hProv,exportKey,pbDataLen,hExportKey,0,&hImportKey))
  178.     {
  179.         ErrorHandling();   
  180.         return -1;
  181.     }
  182.  
  183.     cout << "Key has been imported successfully\n";
  184.  
  185.     string decryptedData = encryptedData;
  186.  
  187.     if (CryptDecrypt(hImportKey,0,TRUE,0,(BYTE *) decryptedData.c_str(),&dataLength))
  188.     {
  189.         cout << "Decrypted successfully\n";
  190.         cout << "Decrypted string: " << decryptedData << endl;
  191.         cout << "Decrypted data length: " << static_cast<int>(dataLength) << endl;
  192.     }
  193.     else
  194.     {
  195.         ErrorHandling();
  196.         return -1;
  197.     }
  198.     // освобождаем память
  199.     if (hProv)
  200.     {
  201.         CryptAcquireContext(&hProv,hName,NULL,PROV_RSA_FULL,CRYPT_DELETEKEYSET);
  202.         CryptReleaseContext(hProv,0);
  203.     }
  204.     if (hSessionKey)
  205.         CryptDestroyKey(hSessionKey);
  206.     if (hExportKey)
  207.         CryptDestroyKey(hExportKey);
  208.     return 0; // succeded
  209. }
  210.  
  211.  
  212. int main(){
  213.     cout << "\t\tSymmetric Encryption Decryption\n";
  214.     if (symmetricED() == 0)
  215.         cout << "Successfully executed symmetric ED\n";
  216.     else
  217.         cout << "Unsuccessfully executed symmetric ED\n";
  218.  
  219.     cout << "\t\tHYDRID Encryption\n";
  220.     hybridED();
  221.     system("pause");
  222.     return 0;
  223. }
Advertisement
Add Comment
Please, Sign In to add comment