just_simple_cryptography/example.cpp
2025-07-27 14:39:29 +03:00

78 lines
2.4 KiB
C++

#include "crypto_lib.hpp"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
try {
cout << "=== Asymmetric Cryptography Example ===" << endl;
string generate_new_keys;
cout << "Generate new keys? (y/n): ";
cin >> generate_new_keys;
string message;
vector<uint8_t> encrypted;
if (generate_new_keys == "y") {
// 1. Generate keys
cout << "1. Generating key pair...\n\n";
auto keys = CryptoLib::generate_keys(2048);
auto& private_key = keys.first;
auto& public_key = keys.second;
// 2. Save keys to files
cout << "2. Saving keys to files...\n\n";
CryptoLib::save_private_key(*private_key, "private_key.pem");
CryptoLib::save_public_key(*public_key, "public_key.pem");
message = "Hello, this is a secret message!";
} else {
cout << "Enter message to decrypt (if exists): ";
cin.ignore();
getline(cin, message);
if (!message.empty()) {
encrypted = CryptoLib::base64_to_bytes(message);
} else {
message = "Hello, this is a secret message!";
}
}
// 3. Load keys from files
cout << "3. Loading keys from files...\n\n";
auto loaded_private_key = CryptoLib::load_private_key("private_key.pem");
auto loaded_public_key = CryptoLib::load_public_key("public_key.pem");
// 4. Convert public key to string and back
cout << "4. Loaded keys:\n";
string private_key_str = CryptoLib::private_key_to_string(*loaded_private_key);
string public_key_str = CryptoLib::public_key_to_string(*loaded_public_key);
cout << "Private key string as: " << private_key_str.substr(0, 50) << "...\n";
cout << "Public key string as: " << public_key_str.substr(0, 50) << "...\n\n";
cout << "5. Convert public key from string...\n\n";
auto restored_public_key = CryptoLib::public_key_from_string(public_key_str);
if (encrypted.empty()) {
// 6. Encrypt data
cout << "6. Testing ecnryption..." << endl;
cout << "Original message: " << message << endl;
encrypted = CryptoLib::encrypt(*loaded_public_key, message);
cout << "Encrypted (base64): " << CryptoLib::bytes_to_base64(encrypted) << endl;
cout << "Encrypted data size: " << encrypted.size() << " bytes\n\n";
}
// 7. Decrypt data
string decrypted_message = CryptoLib::decrypt(*loaded_private_key, encrypted);
cout << "7. Decrypted message: " << decrypted_message << "\n";
} catch (const exception& e) {
cerr << "Error: " << e.what() << endl;
return 1;
}
return 0;
}