#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
#include <memory> // For std::unique_ptr
// OpenSSL headers
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/evp.h> // For EVP_PKEY, EVP_PKEY_CTX
#include <openssl/rand.h> // For RAND_bytes, if needed for other things
// Helper function to handle OpenSSL errors
void handleOpenSSLErrors(const std::string& msg) {
char err_buf[256];
ERR_load_crypto_strings();
ERR_error_string_n(ERR_get_error(), err_buf, sizeof(err_buf));
throw std::runtime_error(msg + ": " + err_buf);
}
// RAII wrapper for EVP_PKEY
struct EvpPkeyDeleter {
void operator()(EVP_PKEY* pkey) const {
if (pkey) EVP_PKEY_free(pkey);
}
};
using EvpPkeyPtr = std::unique_ptr<EVP_PKEY, EvpPkeyDeleter>;
// RAII wrapper for EVP_PKEY_CTX
struct EvpPkeyCtxDeleter {
void operator()(EVP_PKEY_CTX* ctx) const {
if (ctx) EVP_PKEY_CTX_free(ctx);
}
};
using EvpPkeyCtxPtr = std::unique_ptr<EVP_PKEY_CTX, EvpPkeyCtxDeleter>;
// Function to generate an RSA key pair
EvpPkeyPtr generateRSAKeyPair(int bits) {
EvpPkeyPtr pkey(EVP_PKEY_new());
if (!pkey) handleOpenSSLErrors("Failed to create EVP_PKEY");
RSA* rsa = RSA_new();
if (!rsa) handleOpenSSLErrors("Failed to create RSA struct");
// RAII for RSA struct to ensure it's freed if BIGNUM or keygen fails
struct RsaDeleter { void operator()(RSA* r) { RSA_free(r); } };
std::unique_ptr<RSA, RsaDeleter> rsa_ptr(rsa);
BIGNUM* bn = BN_new();
if (!bn) handleOpenSSLErrors("Failed to create BIGNUM");
BN_set_word(bn, RSA_F4); // RSA_F4 is 65537, a common public exponent
if (RSA_generate_key_ex(rsa, bits, bn, nullptr) != 1) {
BN_free(bn);
handleOpenSSLErrors("Failed to generate RSA key pair");
}
BN_free(bn);
if (EVP_PKEY_assign_RSA(pkey.get(), rsa_ptr.release()) != 1) { // pkey now owns rsa
handleOpenSSLErrors("Failed to assign RSA key to EVP_PKEY");
}
return pkey;
}
// RSA-OAEP-SHA256 Encryption
std::vector<unsigned char> rsa_oaep_encrypt(EVP_PKEY* pub_key, const unsigned char* plaintext, size_t plaintext_len) {
if (!pub_key) throw std::invalid_argument("Public key is null");
if (EVP_PKEY_id(pub_key) != EVP_PKEY_RSA) {
throw std::runtime_error("Public key is not an RSA key.");
}
EvpPkeyCtxPtr ctx(EVP_PKEY_CTX_new(pub_key, nullptr));
if (!ctx) handleOpenSSLErrors("Failed to create EVP_PKEY_CTX for encryption");
if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
handleOpenSSLErrors("Failed to initialize encryption context");
}
// Set OAEP padding
if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING) <= 0) {
handleOpenSSLErrors("Failed to set RSA OAEP padding");
}
// Set OAEP hash function to SHA256
if (EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), EVP_sha256()) <= 0) {
handleOpenSSLErrors("Failed to set OAEP MD to SHA256");
}
// Set MGF1 hash function to SHA256 (typically same as OAEP hash)
if (EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), EVP_sha256()) <= 0) {
handleOpenSSLErrors("Failed to set MGF1 MD to SHA256");
}
// Determine buffer length for ciphertext
size_t ciphertext_len;
if (EVP_PKEY_encrypt(ctx.get(), nullptr, &ciphertext_len, plaintext, plaintext_len) <= 0) {
handleOpenSSLErrors("Failed to determine ciphertext length");
}
std::vector<unsigned char> ciphertext(ciphertext_len);
if (EVP_PKEY_encrypt(ctx.get(), ciphertext.data(), &ciphertext_len, plaintext, plaintext_len) <= 0) {
handleOpenSSLErrors("Encryption failed");
}
ciphertext.resize(ciphertext_len); // Adjust vector size if needed
return ciphertext;
}
// RSA-OAEP-SHA256 Decryption
std::vector<unsigned char> rsa_oaep_decrypt(EVP_PKEY* priv_key, const unsigned char* ciphertext, size_t ciphertext_len) {
if (!priv_key) throw std::invalid_argument("Private key is null");
if (EVP_PKEY_id(priv_key) != EVP_PKEY_RSA) {
throw std::runtime_error("Private key is not an RSA key.");
}
EvpPkeyCtxPtr ctx(EVP_PKEY_CTX_new(priv_key, nullptr));
if (!ctx) handleOpenSSLErrors("Failed to create EVP_PKEY_CTX for decryption");
if (EVP_PKEY_decrypt_init(ctx.get()) <= 0) {
handleOpenSSLErrors("Failed to initialize decryption context");
}
// Set OAEP padding
if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING) <= 0) {
handleOpenSSLErrors("Failed to set RSA OAEP padding for decryption");
}
// Set OAEP hash function to SHA256
if (EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), EVP_sha256()) <= 0) {
handleOpenSSLErrors("Failed to set OAEP MD to SHA256 for decryption");
}
// Set MGF1 hash function to SHA256
if (EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), EVP_sha256()) <= 0) {
handleOpenSSLErrors("Failed to set MGF1 MD to SHA256 for decryption");
}
// Determine buffer length for plaintext
size_t plaintext_len;
if (EVP_PKEY_decrypt(ctx.get(), nullptr, &plaintext_len, ciphertext, ciphertext_len) <= 0) {
handleOpenSSLErrors("Failed to determine plaintext length");
}
std::vector<unsigned char> plaintext(plaintext_len);
if (EVP_PKEY_decrypt(ctx.get(), plaintext.data(), &plaintext_len, ciphertext, ciphertext_len) <= 0) {
handleOpenSSLErrors("Decryption failed");
}
plaintext.resize(plaintext_len); // Adjust vector size
return plaintext;
}
// Helper to print byte vector as hex
void print_hex(const std::string& label, const std::vector<unsigned char>& data) {
std::cout << label << ": ";
for (unsigned char byte : data) {
printf("%02x", byte);
}
std::cout << std::endl;
}
int main() {
// Initialize OpenSSL library (optional for newer versions, but good practice)
// OpenSSL_add_all_algorithms(); // Deprecated in OpenSSL 3.0
// ERR_load_crypto_strings(); // Already called in handleOpenSSLErrors
try {
std::cout << "Generating RSA 2048-bit key pair..." << std::endl;
EvpPkeyPtr key_pair = generateRSAKeyPair(2048); // 2048 bits is a common secure size
// For demonstration, we'll use the same EVP_PKEY object for public and private operations.
// In a real scenario, you'd serialize and separate them.
EVP_PKEY* public_key = key_pair.get();
EVP_PKEY* private_key = key_pair.get();
std::string original_message_str = "This is a secret message for RSA-OAEP-SHA256!";
std::vector<unsigned char> original_message(original_message_str.begin(), original_message_str.end());
std::cout << "Original message: " << original_message_str << std::endl;
// Encrypt
std::cout << "\nEncrypting with RSA-OAEP-SHA256..." << std::endl;
std::vector<unsigned char> ciphertext = rsa_oaep_encrypt(
public_key,
original_message.data(),
original_message.size()
);
print_hex("Ciphertext (hex)", ciphertext);
std::cout << "Ciphertext size: " << ciphertext.size() << " bytes" << std::endl;
// Decrypt
std::cout << "\nDecrypting with RSA-OAEP-SHA256..." << std::endl;
std::vector<unsigned char> decrypted_message_vec = rsa_oaep_decrypt(
private_key,
ciphertext.data(),
ciphertext.size()
);
std::string decrypted_message_str(decrypted_message_vec.begin(), decrypted_message_vec.end());
std::cout << "Decrypted message: " << decrypted_message_str << std::endl;
// Verify
if (original_message_str == decrypted_message_str) {
std::cout << "\nSuccess! Original and decrypted messages match." << std::endl;
} else {
std::cout << "\nError! Messages do not match." << std::endl;
}
} catch (const std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
// If it's an OpenSSL error, it might have already printed details
// If not, and we want to ensure OpenSSL details are printed here:
// char err_buf[256];
// ERR_error_string_n(ERR_get_error(), err_buf, sizeof(err_buf));
// std::cerr << "OpenSSL Error: " << err_buf << std::endl;
return 1;
}
// Clean up OpenSSL (optional for newer versions, but good practice)
// EVP_cleanup(); // Deprecated in OpenSSL 3.0
// ERR_free_strings(); // Deprecated in OpenSSL 3.0
// CRYPTO_cleanup_all_ex_data(); // If used explicitly
return 0;
}
#include <iostream>
#include <vector>
#include <string>
#include <algorithm> // For std::reverse, std::copy
#include <iomanip> // For std::hex, std::setw, std::setfill
#include <stdexcept> // For std::runtime_error
#include <random> // For generating random seed (see warning above)
// --- SHA-256 Implementation (Simplified for brevity, many details omitted for a true impl) ---
namespace MyCrypto {
// SHA-256 Constants
const uint32_t SHA256_K[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
uint32_t ROTR(uint32_t x, int n) { return (x >> n) | (x << (32 - n)); }
uint32_t SHR(uint32_t x, int n) { return x >> n; }
uint32_t Ch(uint32_t x, uint32_t y, uint32_t z) { return (x & y) ^ (~x & z); }
uint32_t Maj(uint32_t x, uint32_t y, uint32_t z) { return (x & y) ^ (x & z) ^ (y & z); }
uint32_t Sigma0(uint32_t x) { return ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22); }
uint32_t Sigma1(uint32_t x) { return ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25); }
uint32_t sigma0(uint32_t x) { return ROTR(x, 7) ^ ROTR(x, 18) ^ SHR(x, 3); }
uint32_t sigma1(uint32_t x) { return ROTR(x, 17) ^ ROTR(x, 19) ^ SHR(x, 10); }
void sha256_transform(uint32_t state[8], const unsigned char block[64]) {
uint32_t w[64];
for (int i = 0; i < 16; ++i) {
w[i] = (uint32_t(block[i * 4]) << 24) | (uint32_t(block[i * 4 + 1]) << 16) |
(uint32_t(block[i * 4 + 2]) << 8) | uint32_t(block[i * 4 + 3]);
}
for (int i = 16; i < 64; ++i) {
w[i] = sigma1(w[i - 2]) + w[i - 7] + sigma0(w[i - 15]) + w[i - 16];
}
uint32_t a = state[0];
uint32_t b = state[1];
uint32_t c = state[2];
uint32_t d = state[3];
uint32_t e = state[4];
uint32_t f = state[5];
uint32_t g = state[6];
uint32_t h = state[7];
for (int i = 0; i < 64; ++i) {
uint32_t T1 = h + Sigma1(e) + Ch(e, f, g) + SHA256_K[i] + w[i];
uint32_t T2 = Sigma0(a) + Maj(a, b, c);
h = g;
g = f;
f = e;
e = d + T1;
d = c;
c = b;
b = a;
a = T1 + T2;
}
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
state[5] += f;
state[6] += g;
state[7] += h;
}
std::vector<unsigned char> sha256(const std::vector<unsigned char>& message) {
uint32_t h[8] = {
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
};
std::vector<unsigned char> padded_message = message;
uint64_t original_len_bits = (uint64_t)message.size() * 8;
// Padding: append '1' bit (0x80)
padded_message.push_back(0x80);
// Append '0' bits until message length in bits is 448 (mod 512)
// block size is 512 bits = 64 bytes
// (len + 1 byte for 0x80 + k bytes for 0x00 + 8 bytes for length) % 64 == 0
// (len + 1 + k + 8) % 64 == 0
// (len_bytes + 9 + k) % 64 == 0
// So current length is padded_message.size(). We need total_len % 64 == 56 for the length to be appended
while (padded_message.size() % 64 != 56) {
padded_message.push_back(0x00);
}
// Append original length in bits as 64-bit big-endian integer
for (int i = 7; i >= 0; --i) {
padded_message.push_back((original_len_bits >> (i * 8)) & 0xFF);
}
// Process message in 64-byte chunks
for (size_t i = 0; i < padded_message.size(); i += 64) {
sha256_transform(h, padded_message.data() + i);
}
std::vector<unsigned char> digest(32);
for (int i = 0; i < 8; ++i) {
digest[i * 4 + 0] = (h[i] >> 24) & 0xFF;
digest[i * 4 + 1] = (h[i] >> 16) & 0xFF;
digest[i * 4 + 2] = (h[i] >> 8) & 0xFF;
digest[i * 4 + 3] = (h[i] >> 0) & 0xFF;
}
return digest;
}
// --- MGF1 (Mask Generation Function) ---
// Using SHA-256 as the hash function H
std::vector<unsigned char> mgf1_sha256(const std::vector<unsigned char>& seed, size_t mask_len) {
const size_t hLen = 32; // SHA-256 output length
if (mask_len > (0xFFFFFFFFULL * hLen)) { // (2^32 -1) * hLen
throw std::runtime_error("MGF1: mask too long");
}
std::vector<unsigned char> T;
T.reserve(mask_len + hLen); // Pre-allocate memory to avoid frequent reallocations
for (uint32_t counter = 0; T.size() < mask_len; ++counter) {
std::vector<unsigned char> C(4);
C[0] = (counter >> 24) & 0xFF;
C[1] = (counter >> 16) & 0xFF;
C[2] = (counter >> 8) & 0xFF;
C[3] = counter & 0xFF;
std::vector<unsigned char> seed_plus_C = seed;
seed_plus_C.insert(seed_plus_C.end(), C.begin(), C.end());
std::vector<unsigned char> hash_val = sha256(seed_plus_C);
T.insert(T.end(), hash_val.begin(), hash_val.end());
}
T.resize(mask_len); // Truncate to desired length
return T;
}
// --- Helper: Generate Random Bytes ---
std::vector<unsigned char> generate_random_bytes(size_t len) {
// WARNING: std::mt19937 is NOT cryptographically secure!
// For real applications, use OS-provided CSPRNG (e.g., /dev/urandom, CryptGenRandom).
static std::random_device rd;
static std::mt19937 gen(rd());
std::uniform_int_distribution<> distrib(0, 255);
std::vector<unsigned char> bytes(len);
for (size_t i = 0; i < len; ++i) {
bytes[i] = static_cast<unsigned char>(distrib(gen));
}
return bytes;
}
// --- RSA Primitives (STUBS / VERY SIMPLIFIED - INSECURE) ---
// This is where a Big Integer library would be essential.
// For demonstration, we'll assume 'n' fits in unsigned long long and operations don't overflow,
// which is IMPOSSIBLE for secure RSA key sizes with OAEP-SHA256.
// Placeholder for BigInt modular exponentiation: result = base^exp % mod
// THIS IS A TOY IMPLEMENTATION AND WILL OVERFLOW FOR REAL RSA VALUES
unsigned long long toy_mod_pow(unsigned long long base, unsigned long long exp, unsigned long long mod) {
unsigned long long res = 1;
base %= mod;
while (exp > 0) {
if (exp % 2 == 1) res = (static_cast<unsigned __int128>(res) * base) % mod; // Use __int128 if available for intermediate
base = (static_cast<unsigned __int128>(base) * base) % mod;
exp /= 2;
}
return res;
}
// Placeholder: Convert byte vector to a number (Big-Endian)
// INSECURE: Assumes number fits in unsigned long long
unsigned long long bytes_to_ull(const std::vector<unsigned char>& bytes) {
if (bytes.size() > sizeof(unsigned long long)) {
// This will happen for real RSA-OAEP-SHA256 where EM is k bytes (e.g., 256 bytes for RSA-2048)
// throw std::runtime_error("Cannot convert bytes to ULL: too large for toy implementation.");
// For the sake of trying to run, let's just take the last few bytes, though this is meaningless.
std::cerr << "Warning: bytes_to_ull truncating data due to toy ULL limitation." << std::endl;
unsigned long long num = 0;
size_t start = bytes.size() > 8 ? bytes.size() - 8 : 0;
for (size_t i = start; i < bytes.size(); ++i) {
num = (num << 8) | bytes[i];
}
return num;
}
unsigned long long num = 0;
for (unsigned char byte : bytes) {
num = (num << 8) | byte;
}
return num;
}
// Placeholder: Convert number to byte vector (Big-Endian, fixed size k)
// INSECURE: Assumes number fits, k is small.
std::vector<unsigned char> ull_to_bytes(unsigned long long num, size_t k_bytes) {
std::vector<unsigned char> bytes(k_bytes);
if (k_bytes > sizeof(unsigned long long)) {
std::cerr << "Warning: ull_to_bytes padding extensively due to toy ULL limitation for k_bytes=" << k_bytes << std::endl;
}
for (size_t i = 0; i < k_bytes; ++i) {
// Fill from the right (least significant part of num goes to end of vector)
// This ensures the number is right-aligned in the k_byte array
if (k_bytes - 1 - i < sizeof(unsigned long long)) { // only write if it fits in ULL
bytes[i] = (num >> ( (std::min(k_bytes, sizeof(unsigned long long)) - 1 - (i-(k_bytes-sizeof(unsigned long long))) ) * 8)) & 0xFF;
} else {
bytes[i] = 0; // pad with leading zeros if k_bytes is larger than ULL
}
}
// Fix: correct order for big-endian. Most significant byte first.
std::vector<unsigned char> correct_bytes(k_bytes);
for (size_t i = 0; i < k_bytes; ++i) {
int shift = (k_bytes - 1 - i) * 8;
if (shift < 64) { // ensure shift is valid for ULL
correct_bytes[i] = (num >> shift) & 0xFF;
} else {
correct_bytes[i] = 0; // if k_bytes is too large, these are leading zeros
}
}
return correct_bytes;
}
// --- RSA-OAEP-SHA256 Encryption ---
// k: RSA modulus length in bytes (e.g., 256 for 2048-bit RSA)
// pub_exp, modulus_n: RSA public key components (would be BigInts)
std::vector<unsigned char> rsa_oaep_sha256_encrypt(
const std::vector<unsigned char>& message,
unsigned long long pub_exp, // Toy public exponent
unsigned long long modulus_n, // Toy modulus
size_t k_bytes // Byte length of modulus_n
) {
const size_t hLen = 32; // SHA-256 output length in bytes
// 1. Length checking
if (message.size() > k_bytes - 2 * hLen - 2) {
throw std::runtime_error("Message too long for OAEP padding.");
}
// 2. EME-OAEP encoding
std::vector<unsigned char> L; // Empty label
std::vector<unsigned char> lHash = sha256(L);
size_t ps_len = k_bytes - message.size() - 2 * hLen - 2;
std::vector<unsigned char> PS(ps_len, 0x00);
// DB = lHash || PS || 0x01 || M
std::vector<unsigned char> DB;
DB.reserve(lHash.size() + PS.size() + 1 + message.size());
DB.insert(DB.end(), lHash.begin(), lHash.end());
DB.insert(DB.end(), PS.begin(), PS.end());
DB.push_back(0x01);
DB.insert(DB.end(), message.begin(), message.end());
std::vector<unsigned char> seed = generate_random_bytes(hLen);
std::vector<unsigned char> dbMask = mgf1_sha256(seed, k_bytes - hLen - 1);
std::vector<unsigned char> maskedDB(DB.size());
for (size_t i = 0; i < DB.size(); ++i) {
maskedDB[i] = DB[i] ^ dbMask[i];
}
std::vector<unsigned char> seedMask = mgf1_sha256(maskedDB, hLen);
std::vector<unsigned char> maskedSeed(seed.size());
for (size_t i = 0; i < seed.size(); ++i) {
maskedSeed[i] = seed[i] ^ seedMask[i];
}
// EM = 0x00 || maskedSeed || maskedDB
std::vector<unsigned char> EM;
EM.push_back(0x00);
EM.insert(EM.end(), maskedSeed.begin(), maskedSeed.end());
EM.insert(EM.end(), maskedDB.begin(), maskedDB.end());
// 3. RSA encryption (using toy function)
// C = m^e mod n
// Here, 'm' is the integer representation of EM
unsigned long long m_val = bytes_to_ull(EM); // INSECURE conversion
if (m_val >= modulus_n) {
// This is highly likely if k_bytes is large and modulus_n is small (toy values)
// Or if bytes_to_ull is faulty for large EM.
// For a real RSA, EM (as an integer) must be < n.
// The padding scheme ensures EM is k_bytes long, so as an integer it's < 2^(8*k_bytes).
// n is also k_bytes long, so n is between 2^(8*(k_bytes-1)) and 2^(8*k_bytes).
// It's possible EM (as integer) > n if n is not close to the max value for k_bytes.
// However, PKCS#1 specifies that the integer m from EM must be < n. If not, error.
// This check is often done implicitly or explicitly by RSA libraries.
// Since our k_bytes and modulus_n are for a toy example, this path might be hit.
throw std::runtime_error("RSA Enc: Encoded message integer m >= modulus n. This should not happen with proper RSA parameters relative to k_bytes.");
}
unsigned long long c_val = toy_mod_pow(m_val, pub_exp, modulus_n);
return ull_to_bytes(c_val, k_bytes); // Ciphertext is k_bytes long
}
// --- RSA-OAEP-SHA256 Decryption ---
std::vector<unsigned char> rsa_oaep_sha256_decrypt(
const std::vector<unsigned char>& ciphertext, // EM, k_bytes long
unsigned long long priv_exp, // Toy private exponent
unsigned long long modulus_n, // Toy modulus
size_t k_bytes // Byte length of modulus_n
) {
const size_t hLen = 32; // SHA-256 output length
// 1. Length checking
if (ciphertext.size() != k_bytes) {
throw std::runtime_error("Decryption error: Ciphertext length incorrect.");
}
// As per PKCS#1 v2.2 section 7.1.2: Check if ciphertext representative c is out of range.
// unsigned long long c_val_check = bytes_to_ull(ciphertext);
// if (c_val_check >= modulus_n) {
// throw std::runtime_error("Decryption error: Ciphertext representative out of range.");
// } // This check is problematic with toy ULL conversion.
// 2. RSA decryption (using toy function)
// m = c^d mod n
unsigned long long c_val = bytes_to_ull(ciphertext); // INSECURE conversion
unsigned long long m_prime_val = toy_mod_pow(c_val, priv_exp, modulus_n);
std::vector<unsigned char> EM = ull_to_bytes(m_prime_val, k_bytes); // EM should be k_bytes
// 3. EME-OAEP decoding
std::vector<unsigned char> L; // Empty label
std::vector<unsigned char> lHash = sha256(L);
unsigned char Y = EM[0];
std::vector<unsigned char> maskedSeed(EM.begin() + 1, EM.begin() + 1 + hLen);
std::vector<unsigned char> maskedDB(EM.begin() + 1 + hLen, EM.end());
// Basic size checks before proceeding
if (maskedDB.size() != k_bytes - hLen -1) {
throw std::runtime_error("Decryption error: maskedDB size incorrect.");
}
std::vector<unsigned char> seedMask = mgf1_sha256(maskedDB, hLen);
std::vector<unsigned char> seed(hLen);
for (size_t i = 0; i < hLen; ++i) {
seed[i] = maskedSeed[i] ^ seedMask[i];
}
std::vector<unsigned char> dbMask = mgf1_sha256(seed, k_bytes - hLen - 1);
std::vector<unsigned char> DB(maskedDB.size());
for (size_t i = 0; i < maskedDB.size(); ++i) {
DB[i] = maskedDB[i] ^ dbMask[i];
}
// Parse DB = lHash' || PS || 0x01 || M
// Check lHash'
std::vector<unsigned char> lHash_prime(DB.begin(), DB.begin() + hLen);
bool lHash_ok = (lHash_prime == lHash);
// Find 0x01 separator
size_t separator_idx = 0;
bool separator_found = false;
for (size_t i = hLen; i < DB.size(); ++i) {
if (DB[i] == 0x01) {
separator_idx = i;
separator_found = true;
break;
}
// Also check if PS contains non-zero bytes before 0x01
if (DB[i] != 0x00) { // PS byte is not zero
lHash_ok = false; // PKCS#1: "decoding error" if PS is wrong, can be combined
break;
}
}
// Check Y, lHash, PS (implicitly via separator search), and separator existence
// IMPORTANT: To prevent timing attacks, all checks should be done and errors reported uniformly.
// For this example, we report distinct errors.
bool Y_ok = (Y == 0x00);
bool overall_ok = Y_ok && lHash_ok && separator_found;
if (!overall_ok) { // Simplified check
// Real implementation should not reveal which check failed to avoid Bleichenbacher-style attacks.
throw std::runtime_error("Decryption error: OAEP padding invalid.");
}
return std::vector<unsigned char>(DB.begin() + separator_idx + 1, DB.end());
}
} // namespace MyCrypto
// Helper to print byte vector as hex
void print_hex(const std::string& label, const std::vector<unsigned char>& data) {
std::cout << label << " (len " << data.size() << "): ";
for (unsigned char byte : data) {
std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(byte);
}
std::cout << std::dec << std::endl; // Reset to decimal for subsequent cout
}
int main() {
std::cout << "RSA-OAEP-SHA256 From Scratch Demo (INSECURE - EDUCATIONAL ONLY)" << std::endl;
std::cout << "WARNING: RSA part uses toy numbers and insecure ULL arithmetic." << std::endl;
std::cout << "SHA-256 and OAEP logic are structurally represented." << std::endl << std::endl;
try {
// --- Toy RSA parameters (VERY INSECURE, for demonstration of OAEP structure) ---
// For OAEP with SHA-256, k (modulus byte length) must be >= 2*hLen + 2
// hLen for SHA-256 = 32 bytes. So k >= 2*32 + 2 = 66 bytes.
// This means a modulus of at least 66 * 8 = 528 bits.
// Our toy ULL arithmetic CANNOT handle this.
// We will use k=66, but the RSA math will be symbolic/broken.
const size_t K_BYTES = 66; // Minimum for SHA-256
// These N, E, D are *not* a valid RSA key pair for K_BYTES=66. They are tiny.
// This makes the RSA part completely non-functional for security.
// We are just testing the padding flow.
unsigned long long N_toy = 3233; // (p=61, q=53) -> k_bytes would be 2! Not 66.
unsigned long long E_toy = 17;
unsigned long long D_toy = 2753; // d for N_toy=3233, E_toy=17
std::cout << "Using K_BYTES = " << K_BYTES << " (mimicking a " << K_BYTES * 8 << "-bit RSA modulus)" << std::endl;
std::cout << "Toy N=" << N_toy << ", E=" << E_toy << ", D=" << D_toy << " (these are too small for K_BYTES)" << std::endl;
std::string message_str = "Test message!";
std::vector<unsigned char> message(message_str.begin(), message_str.end());
print_hex("Original Message", message);
std::cout << "\n--- Simulating Encryption ---" << std::endl;
// The encryption will likely throw "Message too long" if K_BYTES is small,
// or "Encoded message integer m >= modulus n" due to toy N.
// Or bytes_to_ull/ull_to_bytes will misbehave.
// Max message length for K_BYTES=66 and hLen=32: 66 - 2*32 - 2 = 0 bytes.
// This means we CANNOT encrypt anything with K_BYTES=66 and real OAEP-SHA256.
// Let's try K_BYTES large enough for a small message. Say K_BYTES = 256 (2048-bit RSA)
// Max message = 256 - 64 - 2 = 190 bytes.
const size_t REALISTIC_K_BYTES = 256; // e.g. 2048-bit RSA
std::cout << "Switching to more realistic K_BYTES = " << REALISTIC_K_BYTES << " for OAEP capacity." << std::endl;
if (message.size() > REALISTIC_K_BYTES - 2 * 32 - 2) {
std::cout << "Message is too long even for K_BYTES=" << REALISTIC_K_BYTES << std::endl;
return 1;
}
std::vector<unsigned char> ciphertext;
try {
ciphertext = MyCrypto::rsa_oaep_sha256_encrypt(message, E_toy, N_toy, REALISTIC_K_BYTES);
print_hex("Ciphertext (EM after toy RSA)", ciphertext);
} catch (const std::runtime_error& e) {
std::cerr << "Encryption failed: " << e.what() << std::endl;
std::cerr << "This is expected due to toy RSA parameters and ULL limitations with realistic K_BYTES." << std::endl;
std::cerr << "The OAEP padding itself (EM) would be generated before the RSA step that fails." << std::endl;
// Let's try to show the EM at least
// Re-run encoding part of rsa_oaep_sha256_encrypt to get EM
const size_t hLen = 32;
std::vector<unsigned char> L_demo;
std::vector<unsigned char> lHash_demo = MyCrypto::sha256(L_demo);
size_t ps_len_demo = REALISTIC_K_BYTES - message.size() - 2 * hLen - 2;
std::vector<unsigned char> PS_demo(ps_len_demo, 0x00);
std::vector<unsigned char> DB_demo;
DB_demo.insert(DB_demo.end(), lHash_demo.begin(), lHash_demo.end());
DB_demo.insert(DB_demo.end(), PS_demo.begin(), PS_demo.end());
DB_demo.push_back(0x01);
DB_demo.insert(DB_demo.end(), message.begin(), message.end());
std::vector<unsigned char> seed_demo = MyCrypto::generate_random_bytes(hLen);
std::vector<unsigned char> dbMask_demo = MyCrypto::mgf1_sha256(seed_demo, REALISTIC_K_BYTES - hLen - 1);
std::vector<unsigned char> maskedDB_demo(DB_demo.size());
for (size_t i = 0; i < DB_demo.size(); ++i) maskedDB_demo[i] = DB_demo[i] ^ dbMask_demo[i];
std::vector<unsigned char> seedMask_demo = MyCrypto::mgf1_sha256(maskedDB_demo, hLen);
std::vector<unsigned char> maskedSeed_demo(seed_demo.size());
for (size_t i = 0; i < seed_demo.size(); ++i) maskedSeed_demo[i] = seed_demo[i] ^ seedMask_demo[i];
std::vector<unsigned char> EM_demo;
EM_demo.push_back(0x00);
EM_demo.insert(EM_demo.end(), maskedSeed_demo.begin(), maskedSeed_demo.end());
EM_demo.insert(EM_demo.end(), maskedDB_demo.begin(), maskedDB_demo.end());
print_hex("Encoded Message (EM) before RSA", EM_demo);
std::cout << "Actual RSA encryption with toy numbers and large K_BYTES will fail ULL conversion." << std::endl;
return 1; // Exit as full cycle can't complete.
}
std::cout << "\n--- Simulating Decryption ---" << std::endl;
std::vector<unsigned char> decrypted_message;
try {
decrypted_message = MyCrypto::rsa_oaep_sha256_decrypt(ciphertext, D_toy, N_toy, REALISTIC_K_BYTES);
print_hex("Decrypted Message", decrypted_message);
std::string decrypted_str(decrypted_message.begin(), decrypted_message.end());
if (decrypted_str == message_str) {
std::cout << "\nSUCCESS (conceptually)! Original and decrypted messages match." << std::endl;
} else {
std::cout << "\nFAILURE! Messages do not match." << std::endl;
}
} catch (const std::runtime_error& e) {
std::cerr << "Decryption failed: " << e.what() << std::endl;
std::cerr << "This is expected if encryption part had issues or due to toy RSA parameters." << std::endl;
}
} catch (const std::exception& e) {
std::cerr << "Unhandled exception: " << e.what() << std::endl;
return 1;
}
return 0;
}