Overview
The Crypto class provides static methods for generating cryptographic keys. RSA key generation uses the OpenSSL EVP API. Post-quantum key generation is a planned feature and currently returns an empty string.
Methods
static std::string generate_rsa()
Generates a 2048-bit RSA private key using the OpenSSL EVP API and serializes it to PEM format.
Parameters: None
Returns: std::string — a PEM-encoded RSA private key beginning with -----BEGIN PRIVATE KEY-----. Returns an empty string "" if any OpenSSL call fails.
std::string pem = Crypto::generate_rsa();
if (pem.empty()) {
std::cerr << "RSA key generation failed\n";
} else {
// pem starts with: -----BEGIN PRIVATE KEY-----
vault.store_key("default-rsa", "rsa", pem);
}
OpenSSL EVP call chain
The following steps are executed in sequence inside generate_rsa():
Create RSA context
EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, nullptr);
Allocates a new key generation context for the RSA algorithm. Returns nullptr on failure.Initialize key generation
EVP_PKEY_keygen_init(ctx);
Prepares the context for key generation. Must be called before setting parameters.Set key size
EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, 2048);
Configures the RSA modulus length to 2048 bits.Generate key pair
EVP_PKEY* pkey = nullptr;
EVP_PKEY_keygen(ctx, &pkey);
Performs the key generation. On success, pkey holds the RSA private key.Serialize to PEM
BIO* bio = BIO_new(BIO_s_mem());
PEM_write_bio_PrivateKey(bio, pkey, nullptr, nullptr, 0, nullptr, nullptr);
Writes the private key in unencrypted PEM format to an in-memory BIO. The PEM string is then read from the BIO and returned.
static std::string pqc_generate()
Planned post-quantum cryptography key generation. Currently a stub.
pqc_generate() always returns an empty string. It is a placeholder for a future Dilithium (or similar) key generation implementation. Do not rely on its output for any cryptographic purpose.
Parameters: None
Returns: std::string — always "". Also prints an error message to standard error.
std::string pq = Crypto::pqc_generate();
// pq == ""
// stderr: error message indicating PQC is not implemented
// Safe usage: check before storing
if (!pq.empty()) {
vault.store_key("default-pq", "dilithium", pq);
}
Complete example
#include "crypto.h"
#include "vault.h"
#include <iostream>
int main() {
Vault vault("vault.db");
vault.init();
// RSA key generation
std::string rsa_pem = Crypto::generate_rsa();
if (rsa_pem.empty()) {
std::cerr << "Failed to generate RSA key\n";
return 1;
}
vault.store_key("default-rsa", "rsa", rsa_pem);
std::cout << "RSA key stored. PEM length: " << rsa_pem.size() << "\n";
// PQC key generation (stub)
std::string pq_key = Crypto::pqc_generate();
// pq_key is always empty; stored as placeholder
vault.store_key("default-pq", "dilithium", pq_key);
return 0;
}