1 #include <openssl/engine.h>
2 #include <openssl/pem.h>
3
4 #include <assert.h>
5 #include <string.h>
6 #include <stdlib.h>
7
8 #include <fstream>
9 #include <iterator>
10 #include <string>
11
12 #ifndef ENGINE_CMD_BASE
13 # error did not get engine.h
14 #endif
15
16 #define TEST_ENGINE_ID "testkeyengine"
17 #define TEST_ENGINE_NAME "dummy test key engine"
18
19 #define PRIVATE_KEY "test/fixtures/keys/agent1-key.pem"
20
21 #ifdef _WIN32
22 # define DEFAULT_VISIBILITY __declspec(dllexport)
23 #else
24 # define DEFAULT_VISIBILITY __attribute__((visibility("default")))
25 #endif
26
27 namespace {
28
EngineInit(ENGINE * engine)29 int EngineInit(ENGINE* engine) {
30 return 1;
31 }
32
EngineFinish(ENGINE * engine)33 int EngineFinish(ENGINE* engine) {
34 return 1;
35 }
36
EngineDestroy(ENGINE * engine)37 int EngineDestroy(ENGINE* engine) {
38 return 1;
39 }
40
LoadFile(const char * filename)41 std::string LoadFile(const char* filename) {
42 std::ifstream file(filename);
43 return std::string(std::istreambuf_iterator<char>(file),
44 std::istreambuf_iterator<char>());
45 }
46
EngineLoadPrivkey(ENGINE * engine,const char * name,UI_METHOD * ui_method,void * callback_data)47 static EVP_PKEY* EngineLoadPrivkey(ENGINE* engine, const char* name,
48 UI_METHOD* ui_method, void* callback_data) {
49 if (strcmp(name, "dummykey") == 0) {
50 std::string key = LoadFile(PRIVATE_KEY);
51 BIO* bio = BIO_new_mem_buf(key.data(), key.size());
52 EVP_PKEY* ret = PEM_read_bio_PrivateKey(bio, nullptr, nullptr, nullptr);
53
54 BIO_vfree(bio);
55 if (ret != nullptr) {
56 return ret;
57 }
58 }
59
60 return nullptr;
61 }
62
bind_fn(ENGINE * engine,const char * id)63 int bind_fn(ENGINE* engine, const char* id) {
64 ENGINE_set_id(engine, TEST_ENGINE_ID);
65 ENGINE_set_name(engine, TEST_ENGINE_NAME);
66 ENGINE_set_init_function(engine, EngineInit);
67 ENGINE_set_finish_function(engine, EngineFinish);
68 ENGINE_set_destroy_function(engine, EngineDestroy);
69 ENGINE_set_load_privkey_function(engine, EngineLoadPrivkey);
70
71 return 1;
72 }
73
74 extern "C" {
75 DEFAULT_VISIBILITY IMPLEMENT_DYNAMIC_CHECK_FN();
76 DEFAULT_VISIBILITY IMPLEMENT_DYNAMIC_BIND_FN(bind_fn);
77 }
78
79 } // anonymous namespace
80