static ENGINE* LoadEngine() { // This function creates an engine for PKCS#11 and inspired by // the "ENGINE_load_dynamic" function from OpenSSL, in file // "crypto/engine/eng_dyn.c" ENGINE* engine = ENGINE_new(); if (!engine) { LOG(ERROR) << "Cannot create an OpenSSL engine for PKCS#11"; throw OrthancException(ErrorCode_InternalError); } // Create a PKCS#11 context using libp11 context_ = pkcs11_new(); if (!context_) { LOG(ERROR) << "Cannot create a libp11 context for PKCS#11"; ENGINE_free(engine); throw OrthancException(ErrorCode_InternalError); } if (!ENGINE_set_id(engine, PKCS11_ENGINE_ID) || !ENGINE_set_name(engine, PKCS11_ENGINE_NAME) || !ENGINE_set_cmd_defns(engine, PKCS11_ENGINE_COMMANDS) || // Register the callback functions !ENGINE_set_init_function(engine, EngineInitialize) || !ENGINE_set_finish_function(engine, EngineFinalize) || !ENGINE_set_destroy_function(engine, EngineDestroy) || !ENGINE_set_ctrl_function(engine, EngineControl) || !ENGINE_set_load_pubkey_function(engine, EngineLoadPublicKey) || !ENGINE_set_load_privkey_function(engine, EngineLoadPrivateKey) || !ENGINE_set_RSA(engine, PKCS11_get_rsa_method()) || !ENGINE_set_ECDSA(engine, PKCS11_get_ecdsa_method()) || !ENGINE_set_ECDH(engine, PKCS11_get_ecdh_method()) || #if OPENSSL_VERSION_NUMBER >= 0x10100002L !ENGINE_set_EC(engine, PKCS11_get_ec_key_method()) || #endif // Make OpenSSL know about our PKCS#11 engine !ENGINE_add(engine)) { LOG(ERROR) << "Cannot initialize the OpenSSL engine for PKCS#11"; pkcs11_finish(context_); ENGINE_free(engine); throw OrthancException(ErrorCode_InternalError); } // If the "ENGINE_add" worked, it gets a structural // reference. We release our just-created reference. ENGINE_free(engine); return ENGINE_by_id(PKCS11_ENGINE_ID); }
static ENGINE_CTX *get_ctx(ENGINE *engine) { ENGINE_CTX *ctx; if (pkcs11_idx < 0) { pkcs11_idx = ENGINE_get_ex_new_index(0, "pkcs11", NULL, NULL, 0); if (pkcs11_idx < 0) return NULL; ctx = NULL; } else { ctx = ENGINE_get_ex_data(engine, pkcs11_idx); } if (ctx == NULL) { ctx = pkcs11_new(); ENGINE_set_ex_data(engine, pkcs11_idx, ctx); } return ctx; }