#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/evp.h>
#include <openssl/bn.h>
#include <iostream>
#include <vector>
#include <string>
#include <nlohmann/json.hpp>
// Decode base64url to binary
std::vector<uint8_t> base64url_decode(const std::string& input) {
std::string base64 = input;
// Convert base64url to base64
std::replace(base64.begin(), base64.end(), '-', '+');
std::replace(base64.begin(), base64.end(), '_', '/');
// Add padding if needed
while (base64.length() % 4 != 0) {
base64.push_back('=');
}
// Use OpenSSL for base64 decoding
BIO* b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
BIO* bmem = BIO_new_mem_buf(base64.c_str(), base64.length());
bmem = BIO_push(b64, bmem);
std::vector<uint8_t> result(base64.length());
int decoded_size = BIO_read(bmem, result.data(), result.size());
result.resize(decoded_size);
BIO_free_all(bmem);
return result;
}
int main() {
// Parse the JWK
nlohmann::json jwk = nlohmann::json::parse(R"({"keys":[{"kty":"RSA","n":"qH2KwwF8sG91CCyu-FvWYPpNgFzmQlOt6NgIDkxLZ0RlGxWnVi0TPd3C1wmua1nYqm54sDrlBmZjMn3VIvboJFo4m2qqKXaLv-AwMy0_QxUuMTCvyExd_632W-uPGq2KgFM1a0-L-akCNNUJGlulOHUxeORg_G34kZSXPfxBa_M4YcPxiJSuI35FLSIfCplDi2qPN0cqHNvLcmdEKgb9DbXqwNhHhhSK5yWLBZlTKyLhIU0HewUJWG-J5GdUZv7dnUzE5Cl2SF4u91LKCLw3nSWoHrHwE-CGoNFNLC3ScBJbkWbLeVeFXNx5YTf2pUR4bVHTrglBwHtMuGq0NDnDiQ","e":"AQAB","alg":"RSA-OAEP-256","enc":"A256GCM","kid":"qK0xIal8gmz2p7A8mVYMrv3YsOo4kD25sB0C6L7dk_Q","use":"enc"}]})");
// Extract key components
auto n_bytes = base64url_decode(jwk["keys"][0]["n"]);
auto e_bytes = base64url_decode(jwk["keys"][0]["e"]);
// Create RSA key
RSA* rsa = RSA_new();
BIGNUM* n = BN_bin2bn(n_bytes.data(), n_bytes.size(), nullptr);
BIGNUM* e = BN_bin2bn(e_bytes.data(), e_bytes.size(), nullptr);
RSA_set0_key(rsa, n, e, nullptr); // No private key, just public
// Create EVP_PKEY
EVP_PKEY* pkey = EVP_PKEY_new();
EVP_PKEY_assign_RSA(pkey, rsa);
// Encrypt a message
std::string plaintext = "Secret message";
// Create encryption context
EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new(pkey, nullptr);
EVP_PKEY_encrypt_init(ctx);
// Set RSA-OAEP-256 padding as specified in the JWK
EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING);
EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256());
// Determine buffer size
size_t outlen;
EVP_PKEY_encrypt(ctx, nullptr, &outlen,
(unsigned char*)plaintext.data(), plaintext.size());
// Encrypt
std::vector<unsigned char> ciphertext(outlen);
EVP_PKEY_encrypt(ctx, ciphertext.data(), &outlen,
(unsigned char*)plaintext.data(), plaintext.size());
// Cleanup
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_free(pkey);
std::cout << "Encryption successful. Ciphertext size: " << outlen << " bytes" << std::endl;
return 0;
}