Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fstream>
- #include <iomanip>
- #include <Windows.h>
- #include <wincrypt.h>
- #include <iostream>
- #include <sstream>
- using namespace std;
- void ErrorHandling() {
- DWORD dw = GetLastError();
- cout << "Error: " << hex << dw << endl;
- }
- string ToHex(const string& s, bool upper_case /* = true */)
- {
- ostringstream ret;
- for (string::size_type i = 0; i < s.length(); ++i)
- ret << std::hex << std::setfill('0') << std::setw(2) << (upper_case ? std::uppercase : std::nouppercase) << (int)s[i];
- return ret.str();
- }
- int main()
- {
- // var section
- cout << "enter string: ";
- string data{}; // входная строка
- cin >> data;
- string encryptedData = data;
- DWORD dataLength = static_cast<DWORD>(data.length()); // её длина
- HCRYPTPROV hProv;
- LPCWSTR hName = L"QAUontainer"; // имя контейнера
- HCRYPTKEY hSessionKey, hExportKey; // ключ сессии и публичный
- HCRYPTKEY hImportKey; // ключ для импорта
- DWORD pbDataLen = 0; // длина массива для экспорта ключа
- cout << "Creating container...\n";
- // создаём контейнер
- if (!CryptAcquireContext(&hProv, hName, nullptr,
- PROV_RSA_FULL, CRYPT_NEWKEYSET))
- {
- ErrorHandling();
- return -1;
- }
- cout << "Container successfully generated!\n";
- // генерируем ключ сессии
- cout << "Generating session key...\n";
- if (!CryptGenKey(hProv, CALG_RC4,
- CRYPT_EXPORTABLE | CRYPT_ENCRYPT | CRYPT_DECRYPT,
- &hSessionKey))
- {
- ErrorHandling();
- return -1;
- }
- cout << "Session key has been generated\n";
- // генерируем ключ для экспорта в данном контексте
- cout << "Generating export key...\n";
- if (!CryptGenKey(hProv, AT_KEYEXCHANGE, 0, &hExportKey))
- {
- ErrorHandling();
- return -1;
- }
- // дескриптор открытого ключа
- if (!CryptGetUserKey(hProv, AT_KEYEXCHANGE, &hExportKey))
- {
- ErrorHandling();
- return -1;
- }
- cout << "Export key has been generated\n";
- // рассчитываем длину для экспорта ключа
- if (!CryptExportKey(hSessionKey, hExportKey, SIMPLEBLOB, 0, NULL, &pbDataLen))
- {
- ErrorHandling();
- return -1;
- }
- BYTE* exportKey = static_cast<BYTE*>(malloc(pbDataLen));
- ZeroMemory(exportKey, pbDataLen);
- // Экспортируем ключ шифрования
- if (!CryptExportKey(hSessionKey, hExportKey, SIMPLEBLOB, 0, exportKey, &pbDataLen))
- {
- ErrorHandling();
- return -1;
- }
- cout << "Key has been exported\n";
- // вывод ключа в 16-ричном виде
- cout << "export key: ";
- stringstream ss;
- ss << hex << setfill('0');
- for (int i = 0; i < pbDataLen; i++)
- ss << setw(2) << static_cast<unsigned>(exportKey[i]);
- cout << ss.str() << endl;
- cout << "Data encryption\n";
- cout << "\t\tInput data\n";
- cout << "Data: " << data << endl;
- cout << "Data length: " << data.length() << endl;
- if (!CryptEncrypt(hSessionKey, 0, TRUE, 0,
- (PBYTE)encryptedData.c_str(), &dataLength, data.length()))
- {
- ErrorHandling();
- return -1;
- }
- cout << "Encrypted successfully\n";
- cout << "Encrypted string: " << ToHex(encryptedData, false) << endl;
- cout << "Encrypted data length:" << static_cast<int>(dataLength) << endl;
- cout << "Data decryption\n";
- cout << "Importing key\n";
- if (!CryptImportKey(hProv, exportKey, pbDataLen, hExportKey, 0, &hImportKey))
- {
- ErrorHandling();
- return -1;
- }
- cout << "Key has been imported successfully\n";
- string decryptedData = encryptedData;
- if (CryptDecrypt(hImportKey, 0, TRUE, 0, (BYTE*)decryptedData.c_str(), &dataLength))
- {
- cout << "Decrypted successfully\n";
- cout << "Decrypted string: " << decryptedData << endl;
- cout << "Decrypted data length: " << static_cast<int>(dataLength) << endl;
- }
- else
- {
- ErrorHandling();
- return -1;
- }
- // освобождаем память
- if (hProv)
- {
- CryptAcquireContext(&hProv, hName, NULL, PROV_RSA_FULL, CRYPT_DELETEKEYSET);
- CryptReleaseContext(hProv, 0);
- }
- if (hSessionKey)
- CryptDestroyKey(hSessionKey);
- if (hExportKey)
- CryptDestroyKey(hExportKey);
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement