CKM: Multithreaded encryption test
[platform/core/test/security-tests.git] / src / ckm / unprivileged / encryption-decryption.cpp
1 /*
2  *  Copyright (c) 2000 - 2019 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *  Licensed under the Apache License, Version 2.0 (the "License");
5  *  you may not use this file except in compliance with the License.
6  *  You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License
15  */
16 /*
17  * @file       encryption-decryption.cpp
18  * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
19  * @version    1.0
20  */
21
22
23 #include <string>
24 #include <vector>
25 #include <unordered_map>
26 #include <thread>
27
28 #include <dpl/test/test_runner.h>
29 #include <ckm-common.h>
30 #include <ckmc/ckmc-manager.h>
31 #include <ckmc/ckmc-control.h>
32 #include <ckm/ckm-type.h>
33 #include <ckm/ckm-manager.h>
34 #include <encryption-decryption-env.h>
35
36 using namespace CKM;
37
38 namespace {
39
40 const char* PASSWORD = "test-password";
41 const uid_t UID = 5001;
42 const size_t CTR_DEFAULT_LEN = 16*8;
43 const size_t DEFAULT_IV_LEN = 16;
44 const size_t BUF_LEN = 86; // must be less than 1024/8-41 to support RSA OAEP 1024
45
46 // Environment
47 SyncApi g_syncApi;
48 AsyncApi g_asyncApi;
49
50 EncryptionApi* g_api = &g_syncApi;
51
52 EncryptionError apiEncrypt(ckmc_param_list_h params,
53                         const char *key_alias,
54                         const char *password,
55                         const ckmc_raw_buffer_s decrypted,
56                         ckmc_raw_buffer_s **ppencrypted) {
57     RUNNER_ASSERT_MSG(g_api, "No encryption API is connected");
58     return g_api->encrypt(params, key_alias, password, decrypted, ppencrypted);
59 }
60
61 inline CKM::Password _tostring(const char *str)
62 {
63     return (str == nullptr) ? Password() : Password(str);
64 }
65
66 inline CKM::Policy _toCkmPolicy(const ckmc_policy_s &policy, PolicyBackend backend)
67 {
68     return CKM::Policy(_tostring(policy.password), policy.extractable, backend);
69 }
70
71 EncryptionError apiDecrypt(ckmc_param_list_h params,
72                         const char *key_alias,
73                         const char *password,
74                         const ckmc_raw_buffer_s encrypted,
75                         ckmc_raw_buffer_s **ppdecrypted) {
76     RUNNER_ASSERT_MSG(g_api, "No encryption API is connected");
77     return g_api->decrypt(params, key_alias, password, encrypted, ppdecrypted);
78 }
79
80
81 template <typename F, typename... Args>
82 void assert_crypto_result(EncryptionError expected, F&& func, Args... args)
83 {
84     EncryptionError ret = func(args...);
85     RUNNER_ASSERT_MSG(ret == expected,
86                       "Expected: " << static_cast<int>(expected) <<
87                       " got: " << static_cast<int>(ret));
88 }
89
90 template <typename F, typename... Args>
91 void assert_crypto_positive(F&& func, Args... args)
92 {
93     assert_crypto_result(EncryptionError::SUCCESS, std::move(func), args...);
94 }
95
96 template <typename F, typename... Args>
97 void assert_crypto_invalid_param(F&& func, Args... args)
98 {
99     assert_crypto_result(EncryptionError::INVALID_PARAM, std::move(func), args...);
100 }
101
102 struct TagTest {
103     int tagLen;
104     EncryptionError expected;
105 };
106
107 struct KeyAliasPair
108 {
109     Alias prv;
110     Alias pub;
111 };
112
113 struct SyncEnv {
114     void init(const std::string&) {
115         g_api = &g_syncApi;
116     }
117
118     void finish() {
119         g_api = nullptr;
120     }
121
122     static std::string suffix() { return "_sync"; }
123 };
124
125 struct AsyncEnv {
126     void init(const std::string&) {
127         g_api = &g_asyncApi;
128     }
129
130     void finish() {
131         g_api = nullptr;
132     }
133
134     static std::string suffix() { return "_async"; }
135 };
136
137 struct Algo {
138     ckmc_algo_type_e type;
139     size_t keyLen;
140 };
141
142 std::unordered_map<size_t, std::vector<Alias>> g_symKeys;
143 std::unordered_map<size_t, std::vector<KeyAliasPair>> g_asymKeys;
144
145 enum KeyIdx {
146     PRIMARY = 0,
147     PASSWORD_PROTECTED = 1,
148
149     KEY_IDX_MAX
150 };
151
152 RawBufferPtr PLAIN_DATA;
153 RawBufferPtr BIG_DATA;
154 ckmc_raw_buffer_s* DEFAULT_IV;
155 ckmc_raw_buffer_s* IV11;
156 ckmc_raw_buffer_s* IV12;
157 ckmc_raw_buffer_s* IV15;
158 ckmc_raw_buffer_s* IV17;
159 ckmc_raw_buffer_s* IV128;
160 ckmc_raw_buffer_s* AAD32;
161 ckmc_raw_buffer_s* AAD64;
162
163 KeyAliasPair getKey(const Algo& algo, KeyIdx idx)
164 {
165     if (algo.type == CKMC_ALGO_RSA_OAEP)
166         return g_asymKeys[algo.keyLen][idx];
167
168     KeyAliasPair pair;
169     pair.prv = g_symKeys[algo.keyLen][idx];
170     pair.pub = pair.prv;
171     return pair;
172 }
173
174 class EncGroupFixture: public DPL::Test::TestGroup
175 {
176 public:
177     void Init() override
178     {
179         remove_user_data(UID);
180         int ret = ckmc_unlock_user_key(UID, "db-pass");
181         if (ret != CKMC_ERROR_NONE)
182             RUNNER_ERROR_MSG("DB unlock failed: " << CKMCErrorToString(ret));
183
184         // Policy backend to use in subsequent operations (global for each test case)
185 #ifdef TZ_BACKEND
186         m_backend = PolicyBackend::FORCE_HARDWARE;
187 #else
188         m_backend = PolicyBackend::FORCE_SOFTWARE;
189 #endif
190
191         // generate keys
192         m_manager = Manager::create();
193         generateSymmetricKeys(128);
194         generateSymmetricKeys(192);
195         generateSymmetricKeys(256);
196         generateRsaKeys(1024);
197         generateRsaKeys(2048);
198         generateRsaKeys(4096);
199
200         PLAIN_DATA = create_raw_buffer(createRandomBufferCAPI(BUF_LEN));
201 #ifdef TZ_BACKEND
202         BIG_DATA = create_raw_buffer(createRandomBufferCAPI(1000));
203 #else
204         BIG_DATA = create_raw_buffer(createRandomBufferCAPI(5000000));
205 #endif
206         DEFAULT_IV = createRandomBufferCAPI(DEFAULT_IV_LEN);
207         IV11 = createRandomBufferCAPI(11);
208         IV12 = createRandomBufferCAPI(12);
209         IV15 = createRandomBufferCAPI(15);
210         IV17 = createRandomBufferCAPI(17);
211         IV128 = createRandomBufferCAPI(128);
212         AAD32 = createRandomBufferCAPI(32);
213         AAD64 = createRandomBufferCAPI(64);
214     }
215
216     void generateSymmetricKeys(size_t bitLen)
217     {
218         for (int i = 0; i < KEY_IDX_MAX; i++)
219         {
220             Policy p(Password(), false, m_backend);
221             if (i == PASSWORD_PROTECTED)
222                 p.password.assign(PASSWORD);
223
224             std::string alias = std::string("skey_") + std::to_string(bitLen) + std::string("_") + std::to_string(i);
225             int ret = m_manager->createKeyAES(bitLen, alias, p);
226             if (ret != CKM_API_SUCCESS)
227                 RUNNER_ERROR_MSG("AES key creation failed");
228
229             g_symKeys[bitLen].push_back(alias);
230         }
231     }
232
233     void generateRsaKeys(size_t bitLen)
234     {
235         for (int i = 0; i < KEY_IDX_MAX; i++)
236         {
237             Policy prvPolicy(Password(), false, m_backend);
238             Policy pubPolicy(Password(), true, m_backend);
239             if (i == PASSWORD_PROTECTED) {
240                 prvPolicy.password.assign(PASSWORD);
241                 pubPolicy.password.assign(PASSWORD);
242             }
243
244             KeyAliasPair alias;
245             alias.prv = std::string("akey_") + std::to_string(bitLen) + std::string("_") + std::to_string(i);
246             alias.pub = std::string("pub") + alias.prv;
247             int ret = m_manager->createKeyPairRSA(bitLen, alias.prv, alias.pub, prvPolicy, pubPolicy);
248             if (ret != CKM_API_SUCCESS)
249                 RUNNER_ERROR_MSG("RSA key creation failed");
250
251             g_asymKeys[bitLen].push_back(alias);
252         }
253     }
254
255     void Finish() override
256     {
257         for (const auto &entry : g_asymKeys) {
258             for (const auto &keyPair : entry.second) {
259                 m_manager->removeAlias(keyPair.prv);
260                 m_manager->removeAlias(keyPair.pub);
261             }
262         }
263
264         for (const auto &entry : g_symKeys) {
265             for (const auto &key : entry.second) {
266                 m_manager->removeAlias(key);
267             }
268         }
269
270         BIG_DATA.reset();
271         PLAIN_DATA.reset();
272         ckmc_buffer_free(AAD64);
273         ckmc_buffer_free(AAD32);
274         ckmc_buffer_free(IV128);
275         ckmc_buffer_free(IV17);
276         ckmc_buffer_free(IV15);
277         ckmc_buffer_free(IV12);
278         ckmc_buffer_free(IV11);
279         ckmc_buffer_free(DEFAULT_IV);
280
281         int ret = ckmc_lock_user_key(UID);
282         if (ret != CKMC_ERROR_NONE)
283             RUNNER_ERROR_MSG("DB lock failed: " << CKMCErrorToString(ret));
284         remove_user_data(UID);
285     }
286 private:
287     ManagerShPtr m_manager;
288     PolicyBackend m_backend;
289 };
290
291
292 void setParam(ParamListPtr& params, ckmc_param_name_e name, ckmc_raw_buffer_s* buffer)
293 {
294     int ret = ckmc_param_list_set_buffer(params.get(), name, buffer);
295     RUNNER_ASSERT_MSG(ret == CKMC_ERROR_NONE,
296                       "Failed to set param " << name << " error: " << CKMCErrorToString(ret));
297 }
298
299 void setParam(ParamListPtr& params, ckmc_param_name_e name, int integer)
300 {
301     int ret = ckmc_param_list_set_integer(params.get(), name, integer);
302     RUNNER_ASSERT_MSG(ret == CKMC_ERROR_NONE,
303                       "Failed to set param " << name << " error: " << CKMCErrorToString(ret));
304 }
305
306 struct EncryptionResult
307 {
308     RawBufferPtr encrypted;
309     ParamListPtr params;
310     Alias prvKey;
311     Alias pubKey;
312 };
313
314 EncryptionResult encrypt(const Algo& algo,
315                          const RawBufferPtr& plain,
316                          const char* pass = nullptr)
317 {
318     EncryptionResult ret;
319     ckmc_raw_buffer_s* encrypted = nullptr;
320     KeyAliasPair aliases = getKey(algo, pass == nullptr ? PRIMARY : PASSWORD_PROTECTED);
321
322     ckmc_param_list_h handle = NULL;
323     assert_positive(ckmc_generate_new_params, algo.type, &handle);
324     ret.params = ParamListPtr(handle, ckmc_param_list_free);
325     setParam(ret.params, CKMC_PARAM_ED_IV, DEFAULT_IV);
326
327     assert_crypto_positive(apiEncrypt,
328                            ret.params.get(),
329                            aliases.pub.c_str(),
330                            pass,
331                            *plain.get(),
332                            &encrypted);
333
334     ret.encrypted = create_raw_buffer(encrypted);
335     ret.prvKey = aliases.prv;
336     ret.pubKey = aliases.pub;
337     return ret;
338 }
339
340 void testAllAlgorithms(
341         const std::function<void(const Algo& algo)>& test)
342 {
343     test( { CKMC_ALGO_AES_CBC, 128 });
344     test( { CKMC_ALGO_AES_CBC, 192 });
345     test( { CKMC_ALGO_AES_CBC, 256 });
346     test( { CKMC_ALGO_AES_GCM, 128 });
347     test( { CKMC_ALGO_AES_GCM, 192 });
348     test( { CKMC_ALGO_AES_GCM, 256 });
349     test( { CKMC_ALGO_AES_CTR, 128 });
350     test( { CKMC_ALGO_AES_CTR, 192 });
351     test( { CKMC_ALGO_AES_CTR, 256 });
352     test( { CKMC_ALGO_AES_CFB, 128 });
353     test( { CKMC_ALGO_AES_CFB, 192 });
354     test( { CKMC_ALGO_AES_CFB, 256 });
355     test( { CKMC_ALGO_RSA_OAEP, 1024 });
356     test( { CKMC_ALGO_RSA_OAEP, 2048 });
357     test( { CKMC_ALGO_RSA_OAEP, 4096 });
358 }
359
360 void testNoIvEnc(const Algo& algo)
361 {
362     // prepare buffers
363     ckmc_raw_buffer_s* encrypted = nullptr;
364
365     // add key
366     KeyAliasPair aliases = getKey(algo, PRIMARY);
367
368     // param list with algo type only
369     ParamListPtr params = createParamListPtr();
370     setParam(params, CKMC_PARAM_ALGO_TYPE, algo.type);
371     assert_crypto_invalid_param(apiEncrypt,
372                                 params.get(),
373                                 aliases.pub.c_str(),
374                                 nullptr,
375                                 *PLAIN_DATA.get(),
376                                 &encrypted);
377 }
378
379 void testNoIvDec(const Algo& algo)
380 {
381     // prepare buffers
382     ckmc_raw_buffer_s* decrypted = nullptr;
383
384     // encrypt;
385     auto ret = encrypt(algo, PLAIN_DATA);
386
387     // param list with algo type only
388     ParamListPtr params = createParamListPtr();
389     setParam(params, CKMC_PARAM_ALGO_TYPE, algo.type);
390     assert_crypto_invalid_param(apiDecrypt,
391                                 params.get(),
392                                 ret.prvKey.c_str(),
393                                 nullptr,
394                                 *ret.encrypted.get(),
395                                 &decrypted);
396 }
397
398 void testInvalidIvEnc(const Algo& algo)
399 {
400     // prepare buffers
401     ckmc_raw_buffer_s* encryptedTmp = nullptr;
402
403     // add key
404     KeyAliasPair aliases = getKey(algo, PRIMARY);
405
406     // setup params
407     ckmc_param_list_h handle = NULL;
408     assert_positive(ckmc_generate_new_params, algo.type, &handle);
409     ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
410
411     // invalid encryption
412     auto test = [&](){
413         assert_crypto_invalid_param(apiEncrypt,
414                                     params.get(),
415                                     aliases.pub.c_str(),
416                                     nullptr,
417                                     *PLAIN_DATA.get(),
418                                     &encryptedTmp);
419         ckmc_buffer_free(encryptedTmp);
420         encryptedTmp = nullptr;
421     };
422     // invalid iv size
423     setParam(params, CKMC_PARAM_ED_IV, IV15);
424     test();
425     setParam(params, CKMC_PARAM_ED_IV, IV17);
426     test();
427 };
428
429 void testInvalidIvDec(const Algo& algo)
430 {
431     // prepare buffers
432     ckmc_raw_buffer_s* decrypted = nullptr;
433
434     // valid encryption
435     auto ret = encrypt(algo, PLAIN_DATA);
436
437     // decryption
438     auto test2 = [&](){
439         assert_crypto_invalid_param(apiDecrypt,
440                                     ret.params.get(),
441                                     ret.prvKey.c_str(),
442                                     nullptr,
443                                     *ret.encrypted.get(),
444                                     &decrypted);
445         ckmc_buffer_free(decrypted);
446         decrypted = nullptr;
447     };
448
449     // invalid iv size
450     setParam(ret.params, CKMC_PARAM_ED_IV, IV15);
451     test2();
452     setParam(ret.params, CKMC_PARAM_ED_IV, IV17);
453     test2();
454 };
455
456 void encryptionWithCustomData(const Algo& algo, ckmc_param_name_e name)
457 {
458     // prepare buffers
459     ckmc_raw_buffer_s* encrypted = nullptr;
460     ckmc_raw_buffer_s* decrypted = nullptr;
461
462     // add key
463     KeyAliasPair aliases = getKey(algo, PRIMARY);
464
465     // setup params
466     ckmc_param_list_h handle = NULL;
467     assert_positive(ckmc_generate_new_params, algo.type, &handle);
468     ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
469
470     setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
471
472     // set AAD
473     setParam(params, name, AAD64);
474
475     // encrypt
476     assert_crypto_positive(apiEncrypt,
477                            params.get(),
478                            aliases.pub.c_str(),
479                            nullptr,
480                            *PLAIN_DATA.get(),
481                            &encrypted);
482     RawBufferPtr tmpEnc = create_raw_buffer(encrypted);
483
484     // decrypt
485     assert_crypto_positive(apiDecrypt,
486                            params.get(),
487                            aliases.prv.c_str(),
488                            nullptr,
489                            *tmpEnc.get(),
490                            &decrypted);
491     RawBufferPtr tmpDec = create_raw_buffer(decrypted);
492
493     // check
494     assert_buffers_equal(*PLAIN_DATA.get(), *tmpDec.get());
495     tmpDec.reset();
496     decrypted = nullptr;
497
498     // set wrong AAD
499     setParam(params, name, AAD32);
500
501     // decrypt
502     assert_crypto_result(EncryptionError::INVALID_PARAM,
503                          apiDecrypt,
504                          params.get(),
505                          aliases.prv.c_str(),
506                          nullptr,
507                          *tmpEnc.get(),
508                          &decrypted);
509 }
510
511 void testGcmIvSize(ckmc_raw_buffer_s* iv,
512                    const KeyAliasPair& aliases,
513                    EncryptionError error = EncryptionError::SUCCESS)
514 {
515     // prepare buffers
516     RawBufferPtr encrypted;
517     RawBufferPtr decrypted;
518     ckmc_raw_buffer_s* encryptedTmp = nullptr;
519     ckmc_raw_buffer_s* decryptedTmp = nullptr;
520
521     // setup params
522     ckmc_param_list_h handle = NULL;
523     assert_positive(ckmc_generate_new_params, CKMC_ALGO_AES_GCM, &handle);
524     ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
525     setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
526     setParam(params, CKMC_PARAM_ED_IV, iv);
527
528     // encryption
529     assert_crypto_result(error,
530                          apiEncrypt,
531                          params.get(),
532                          aliases.pub.c_str(),
533                          nullptr,
534                          *PLAIN_DATA.get(),
535                          &encryptedTmp);
536
537     if(error != EncryptionError::SUCCESS)
538         return;
539     encrypted = create_raw_buffer(encryptedTmp);
540
541     // decryption
542     assert_crypto_positive(apiDecrypt,
543                            params.get(),
544                            aliases.prv.c_str(),
545                            nullptr,
546                            *encrypted.get(),
547                            &decryptedTmp);
548     decrypted = create_raw_buffer(decryptedTmp);
549
550     assert_buffers_equal(*PLAIN_DATA.get(), *decrypted.get());
551 }
552
553 void testIntegrity(const Algo& algo)
554 {
555     // prepare buffers
556     ckmc_raw_buffer_s* decrypted = nullptr;
557
558     // encrypt
559     auto ret = encrypt(algo, PLAIN_DATA);
560
561     // break the encrypted data
562     ret.encrypted->data[BUF_LEN/2]++;
563
564     // no data integrity check
565     assert_crypto_positive(apiDecrypt,
566                            ret.params.get(),
567                            ret.prvKey.c_str(),
568                            nullptr,
569                            *ret.encrypted.get(),
570                            &decrypted);
571
572     RawBufferPtr tmp = create_raw_buffer(decrypted);
573     assert_buffers_equal(*PLAIN_DATA.get(), *decrypted, false);
574 }
575
576 void testCtrEncryptionInvalidLength(const Algo& algo)
577 {
578     // prepare buffers
579     ckmc_raw_buffer_s* encryptedTmp = nullptr;
580
581     // add AES CTR key
582     KeyAliasPair aliases = getKey(algo, PRIMARY);
583
584     // setup params
585     ckmc_param_list_h handle = NULL;
586     assert_positive(ckmc_generate_new_params, algo.type, &handle);
587     ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
588     setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
589
590     // encryption
591     auto test = [&](){
592         assert_crypto_invalid_param(apiEncrypt,
593                                     params.get(),
594                                     aliases.pub.c_str(),
595                                     nullptr,
596                                     *PLAIN_DATA.get(),
597                                     &encryptedTmp);
598         ckmc_buffer_free(encryptedTmp);
599         encryptedTmp = nullptr;
600     };
601     // invalid counter size
602     setParam(params, CKMC_PARAM_ED_CTR_LEN, -1);
603     test();
604     setParam(params, CKMC_PARAM_ED_CTR_LEN, 0);
605     test();
606     setParam(params, CKMC_PARAM_ED_CTR_LEN, CTR_DEFAULT_LEN+1);
607     test();
608 }
609
610 void testCtrEncryptionValidLength(const Algo& algo)
611 {
612     // prepare buffers
613     ckmc_raw_buffer_s* encryptedTmp = nullptr;
614
615     // add AES CTR key
616     KeyAliasPair aliases = getKey(algo, PRIMARY);
617
618     // setup params
619     ckmc_param_list_h handle = NULL;
620     assert_positive(ckmc_generate_new_params, algo.type, &handle);
621     ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
622     setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
623
624     // encryption
625     auto test = [&](){
626         assert_crypto_positive(apiEncrypt,
627                                params.get(),
628                                aliases.pub.c_str(),
629                                nullptr,
630                                *PLAIN_DATA.get(),
631                                &encryptedTmp);
632         ckmc_buffer_free(encryptedTmp);
633         encryptedTmp = nullptr;
634     };
635     // valid counter sizez
636     setParam(params, CKMC_PARAM_ED_CTR_LEN, 1);
637     test();
638     setParam(params, CKMC_PARAM_ED_CTR_LEN, 4);
639     test();
640     setParam(params, CKMC_PARAM_ED_CTR_LEN, CTR_DEFAULT_LEN-1);
641     test();
642     setParam(params, CKMC_PARAM_ED_CTR_LEN, CTR_DEFAULT_LEN);
643     test();
644 }
645
646 void testCtrDecryptionInvalidLength(const Algo& algo)
647 {
648     // prepare buffers
649     ckmc_raw_buffer_s* decrypted = nullptr;
650
651     // add AES CTR key & encrypt
652     auto ret = encrypt(algo, PLAIN_DATA);
653
654     // decryption
655     auto test = [&](){
656         assert_crypto_invalid_param(apiDecrypt,
657                                     ret.params.get(),
658                                     ret.prvKey.c_str(),
659                                     nullptr,
660                                     *ret.encrypted.get(),
661                                     &decrypted);
662         ckmc_buffer_free(decrypted);
663         decrypted = nullptr;
664     };
665     // invalid counter size
666     setParam(ret.params, CKMC_PARAM_ED_CTR_LEN, -1);
667     test();
668     setParam(ret.params, CKMC_PARAM_ED_CTR_LEN, 0);
669     test();
670     setParam(ret.params, CKMC_PARAM_ED_CTR_LEN, CTR_DEFAULT_LEN+1);
671     test();
672 }
673
674 void testCtrDecryptionValidLength(const Algo& algo)
675 {
676     // prepare buffers
677     ckmc_raw_buffer_s* decrypted = nullptr;
678
679     // add AES CTR key & encrypt
680     auto ret = encrypt(algo, PLAIN_DATA);
681
682     // decryption
683     auto test = [&](){
684         assert_crypto_positive(apiDecrypt,
685                                ret.params.get(),
686                                ret.prvKey.c_str(),
687                                nullptr,
688                                *ret.encrypted.get(),
689                                &decrypted);
690         ckmc_buffer_free(decrypted);
691         RawBufferPtr tmp = create_raw_buffer(decrypted);
692         assert_buffers_equal(*PLAIN_DATA.get(), *decrypted);
693     };
694     // invalid counter size
695     setParam(ret.params, CKMC_PARAM_ED_CTR_LEN, 1);
696     test();
697     setParam(ret.params, CKMC_PARAM_ED_CTR_LEN, 4);
698     test();
699     setParam(ret.params, CKMC_PARAM_ED_CTR_LEN, CTR_DEFAULT_LEN-1);
700     test();
701     setParam(ret.params, CKMC_PARAM_ED_CTR_LEN, CTR_DEFAULT_LEN);
702     test();
703 }
704
705 void testGcmEncryptionTagLen(const Algo& algo)
706 {
707     // prepare buffers
708     ckmc_raw_buffer_s* encryptedTmp = nullptr;
709
710     // add AES GCM key
711     KeyAliasPair aliases = getKey(algo, PRIMARY);
712
713     // setup params
714     ckmc_param_list_h handle = NULL;
715     assert_positive(ckmc_generate_new_params, algo.type, &handle);
716     ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
717     setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
718
719     std::vector<TagTest> testData = {
720             // illegal tag lengths
721             { -1,   EncryptionError::INVALID_PARAM },
722             { 0,    EncryptionError::INVALID_PARAM },
723             { 16,   EncryptionError::INVALID_PARAM },
724             { 48,   EncryptionError::INVALID_PARAM },
725             { 72,   EncryptionError::INVALID_PARAM },
726             { 100,  EncryptionError::INVALID_PARAM },
727             { 108,  EncryptionError::INVALID_PARAM },
728             { 116,  EncryptionError::INVALID_PARAM },
729             { 124,  EncryptionError::INVALID_PARAM },
730             { 256,  EncryptionError::INVALID_PARAM },
731 #ifdef TZ_BACKEND
732             { 32,   EncryptionError::INVALID_PARAM },
733             { 64,   EncryptionError::INVALID_PARAM },
734             // legal tag lengths
735 #else
736             // legal tag lengths
737             { 32,   EncryptionError::SUCCESS },
738             { 64,   EncryptionError::SUCCESS },
739 #endif
740
741             { 96,   EncryptionError::SUCCESS },
742             { 104,  EncryptionError::SUCCESS },
743             { 112,  EncryptionError::SUCCESS },
744             { 120,  EncryptionError::SUCCESS },
745             { 128,  EncryptionError::SUCCESS },
746     };
747
748     // encryption
749     for(const auto& it : testData)
750     {
751         setParam(params, CKMC_PARAM_ED_TAG_LEN, it.tagLen);
752         assert_crypto_result(it.expected,
753                              apiEncrypt,
754                              params.get(),
755                              aliases.pub.c_str(),
756                              nullptr,
757                              *PLAIN_DATA.get(),
758                              &encryptedTmp);
759         ckmc_buffer_free(encryptedTmp);
760         encryptedTmp = nullptr;
761     }
762 }
763
764 void testGcmDecryptionTagLen(const Algo& algo)
765 {
766     // prepare buffers
767     ckmc_raw_buffer_s* decrypted = nullptr;
768
769     // add AES GCM key & encrypt
770     auto ret = encrypt(algo, PLAIN_DATA);
771
772     std::vector<TagTest> testData = {
773             // illegal tag lengths
774             { -1,   EncryptionError::INVALID_PARAM },
775             { 0,    EncryptionError::INVALID_PARAM },
776             { 16,   EncryptionError::INVALID_PARAM },
777             { 48,   EncryptionError::INVALID_PARAM },
778             { 72,   EncryptionError::INVALID_PARAM },
779             { 100,  EncryptionError::INVALID_PARAM },
780             { 108,  EncryptionError::INVALID_PARAM },
781             { 116,  EncryptionError::INVALID_PARAM },
782             { 124,  EncryptionError::INVALID_PARAM },
783             { 256,  EncryptionError::INVALID_PARAM },
784             // legal tag lengths but different than the one used for encryption
785             { 32,   EncryptionError::INVALID_PARAM },
786             { 64,   EncryptionError::INVALID_PARAM },
787             { 96,   EncryptionError::INVALID_PARAM },
788             { 104,  EncryptionError::INVALID_PARAM },
789             { 112,  EncryptionError::INVALID_PARAM },
790             { 120,  EncryptionError::INVALID_PARAM },
791             // legal tag length that was actually used for encryption (default)
792             { 128,  EncryptionError::SUCCESS },
793     };
794
795     // decryption
796     for(const auto& it : testData)
797     {
798         setParam(ret.params, CKMC_PARAM_ED_TAG_LEN, it.tagLen);
799         assert_crypto_result(it.expected,
800                              apiDecrypt,
801                              ret.params.get(),
802                              ret.prvKey.c_str(),
803                              nullptr,
804                              *ret.encrypted.get(),
805                              &decrypted);
806         ckmc_buffer_free(decrypted);
807         decrypted = nullptr;
808     }
809 }
810
811 void testGcmWrongTag(const Algo& algo)
812 {
813     // prepare buffers
814     ckmc_raw_buffer_s* decrypted = nullptr;
815
816     // encrypt with AES GCM
817     auto ret = encrypt(algo, PLAIN_DATA);
818
819     // modify tag (last 16B of encrypted message)
820     ret.encrypted->data[ret.encrypted->size-1]++;
821
822     // EVP_CipherFinal fails because of an authentication error
823     assert_crypto_result(EncryptionError::INVALID_PARAM,
824                          apiDecrypt,
825                          ret.params.get(),
826                          ret.prvKey.c_str(),
827                          nullptr,
828                          *ret.encrypted.get(),
829                          &decrypted);
830 }
831
832 void testGcmDifferentIvSizes(const Algo& algo)
833 {
834     // add AES GCM key
835     KeyAliasPair aliases = getKey(algo, PRIMARY);
836
837     testGcmIvSize(IV11,  aliases, EncryptionError::SERVER_ERROR); // 12B is the smallest
838     testGcmIvSize(IV12,  aliases);
839     testGcmIvSize(IV17,  aliases);
840     testGcmIvSize(IV128, aliases);
841 }
842
843 void testEncryptDecryptBigData(const Algo& algo)
844 {
845     // prepare buffers
846     ckmc_raw_buffer_s* decrypted = nullptr;
847
848     // encrypt
849     auto ret = encrypt(algo, BIG_DATA);
850
851     assert_positive(apiDecrypt,
852                     ret.params.get(),
853                     ret.prvKey.c_str(),
854                     nullptr,
855                     *ret.encrypted.get(),
856                     &decrypted);
857     RawBufferPtr tmp = create_raw_buffer(decrypted);
858
859     assert_buffers_equal(*BIG_DATA.get(), *decrypted);
860 }
861
862 void testEncryptDecryptDifferentKeys(const Algo& algo, bool success)
863 {
864     // prepare buffers
865     ckmc_raw_buffer_s* decrypted = nullptr;
866
867     // encrypt
868     auto ret = encrypt(algo, PLAIN_DATA);
869
870     // get different keys
871     KeyAliasPair differentKeys = getKey(algo, PASSWORD_PROTECTED);
872
873     if (success) {
874         // some algorithms don't verify key validity
875         assert_crypto_positive(apiDecrypt,
876                                ret.params.get(),
877                                differentKeys.prv.c_str(),
878                                PASSWORD,
879                                *ret.encrypted.get(),
880                                &decrypted);
881         RawBufferPtr tmp = create_raw_buffer(decrypted);
882
883         assert_buffers_equal(*PLAIN_DATA.get(), *decrypted, false);
884     } else {
885         assert_crypto_result(EncryptionError::INVALID_PARAM,
886                              apiDecrypt,
887                              ret.params.get(),
888                              differentKeys.prv.c_str(),
889                              PASSWORD,
890                              *ret.encrypted.get(),
891                              &decrypted);
892     }
893 }
894
895 void testRsaLongestData(const Algo& algo, size_t dataSize)
896 {
897     // prepare buffers
898     RawBufferPtr plain = create_raw_buffer(createRandomBufferCAPI(dataSize));
899     ckmc_raw_buffer_s* decrypted = nullptr;
900
901     // encrypt
902     auto ret = encrypt(algo, plain);
903
904     assert_crypto_positive(apiDecrypt,
905                            ret.params.get(),
906                            ret.prvKey.c_str(),
907                            nullptr,
908                            *ret.encrypted.get(),
909                            &decrypted);
910     RawBufferPtr tmp = create_raw_buffer(decrypted);
911
912     assert_buffers_equal(*plain.get(), *decrypted);
913 }
914
915 void testRsaDataTooLong(const Algo& algo, size_t dataSize)
916 {
917     // prepare buffers
918     RawBufferPtr plain = create_raw_buffer(createRandomBufferCAPI(dataSize));
919
920     // encrypt
921     EncryptionResult ret;
922     ckmc_raw_buffer_s* encrypted = nullptr;
923     KeyAliasPair aliases = getKey(algo, PRIMARY);
924
925     ckmc_param_list_h handle = NULL;
926     assert_positive(ckmc_generate_new_params, algo.type, &handle);
927     ret.params = ParamListPtr(handle, ckmc_param_list_free);
928     assert_crypto_result(EncryptionError::INVALID_PARAM,
929                          apiEncrypt,
930                          ret.params.get(),
931                          aliases.pub.c_str(),
932                          nullptr,
933                          *plain.get(),
934                          &encrypted);
935 }
936
937 } // namespace anonymous
938
939 RUNNER_TEST_GROUP_INIT_ENV(CKM_ENCRYPTION_DECRYPTION, EncGroupFixture);
940
941 /////////////////////////////////////////
942 // Generic encryption decryption tests
943 /////////////////////////////////////////
944
945 RUNNER_TEST_MULTIPLE(TED_0010_encrypt_invalid_param_list, SyncEnv, AsyncEnv)
946 {
947     testAllAlgorithms([](const Algo& algo){
948         // prepare buffers
949         ckmc_raw_buffer_s* encrypted = nullptr;
950
951         // add key
952         KeyAliasPair aliases = getKey(algo, PRIMARY);
953
954         // null param list
955         assert_crypto_invalid_param(apiEncrypt,
956                                     nullptr,
957                                     aliases.pub.c_str(),
958                                     nullptr,
959                                     *PLAIN_DATA.get(),
960                                     &encrypted);
961
962         // empty param list
963         ParamListPtr params = createParamListPtr();
964         assert_crypto_invalid_param(apiEncrypt,
965                                     params.get(),
966                                     aliases.pub.c_str(),
967                                     nullptr,
968                                     *PLAIN_DATA.get(),
969                                     &encrypted);
970     });
971 }
972
973 RUNNER_TEST_MULTIPLE(TED_0020_encrypt_missing_key, SyncEnv, AsyncEnv)
974 {
975     testAllAlgorithms([](const Algo& algo){
976         // prepare buffers
977         ckmc_raw_buffer_s* encrypted = nullptr;
978
979         // setup params
980         ckmc_param_list_h handle = NULL;
981         assert_positive(ckmc_generate_new_params, algo.type, &handle);
982         ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
983         setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
984
985         assert_crypto_result(EncryptionError::ALIAS_UNKNOWN,
986                              apiEncrypt,
987                              params.get(),
988                              "non-existing-key-alias",
989                              nullptr,
990                              *PLAIN_DATA.get(),
991                              &encrypted);
992     });
993 }
994
995 RUNNER_TEST_MULTIPLE(TED_0030_encrypt_no_plain_text, SyncEnv, AsyncEnv)
996 {
997     testAllAlgorithms([](const Algo& algo){
998         // prepare buffers
999         ckmc_raw_buffer_s plain = { nullptr, 0 };
1000         ckmc_raw_buffer_s* encrypted = nullptr;
1001
1002         // add key
1003         KeyAliasPair aliases = getKey(algo, PRIMARY);
1004
1005         // setup params
1006         ckmc_param_list_h handle = NULL;
1007         assert_positive(ckmc_generate_new_params, algo.type, &handle);
1008         ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
1009         setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
1010
1011         assert_crypto_invalid_param(apiEncrypt,
1012                                     params.get(),
1013                                     aliases.pub.c_str(),
1014                                     nullptr,
1015                                     plain,
1016                                     &encrypted);
1017     });
1018 }
1019
1020 RUNNER_TEST_MULTIPLE(TED_0040_encrypt_no_output_buffer, SyncEnv, AsyncEnv)
1021 {
1022     testAllAlgorithms([](const Algo& algo){
1023         // prepare buffers
1024         ckmc_raw_buffer_s** encrypted = nullptr;
1025
1026         // add key
1027         KeyAliasPair aliases = getKey(algo, PRIMARY);
1028
1029         // setup params
1030         ckmc_param_list_h handle = NULL;
1031         assert_positive(ckmc_generate_new_params, algo.type, &handle);
1032         ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
1033         setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
1034
1035         assert_crypto_invalid_param(apiEncrypt,
1036                                     params.get(),
1037                                     aliases.pub.c_str(),
1038                                     nullptr,
1039                                     *PLAIN_DATA.get(),
1040                                     encrypted);
1041     });
1042 }
1043
1044 RUNNER_TEST_MULTIPLE(TED_0110_decrypt_invalid_param_list, SyncEnv, AsyncEnv)
1045 {
1046     testAllAlgorithms([](const Algo& algo){
1047         // prepare buffers
1048         ckmc_raw_buffer_s* decrypted = nullptr;
1049
1050         // encrypt;
1051         auto ret = encrypt(algo, PLAIN_DATA);
1052
1053         // null param list
1054         assert_crypto_invalid_param(apiDecrypt,
1055                                     nullptr,
1056                                     ret.prvKey.c_str(),
1057                                     nullptr,
1058                                     *ret.encrypted.get(),
1059                                     &decrypted);
1060
1061         // empty param list
1062         ParamListPtr params = createParamListPtr();
1063         assert_crypto_invalid_param(apiDecrypt,
1064                                     params.get(),
1065                                     ret.prvKey.c_str(),
1066                                     nullptr,
1067                                     *ret.encrypted.get(),
1068                                     &decrypted);
1069     });
1070 }
1071
1072 RUNNER_TEST_MULTIPLE(TED_0120_decrypt_missing_key, SyncEnv, AsyncEnv)
1073 {
1074     testAllAlgorithms([](const Algo& algo){
1075         // prepare buffers
1076         ckmc_raw_buffer_s* decrypted = nullptr;
1077
1078         // encrypt
1079         auto ret = encrypt(algo, PLAIN_DATA);
1080
1081         // try to decrypt
1082         assert_crypto_result(EncryptionError::ALIAS_UNKNOWN,
1083                              apiDecrypt,
1084                              ret.params.get(),
1085                              "non-existent-key",
1086                              nullptr,
1087                              *ret.encrypted.get(),
1088                              &decrypted);
1089     });
1090 }
1091
1092 RUNNER_TEST_MULTIPLE(TED_0130_decrypt_no_encrypted_text, SyncEnv, AsyncEnv)
1093 {
1094     testAllAlgorithms([](const Algo& algo){
1095         // prepare buffers
1096         ckmc_raw_buffer_s encrypted = { nullptr, 0 };
1097         ckmc_raw_buffer_s* decrypted = nullptr;
1098
1099         // add key
1100         KeyAliasPair aliases = getKey(algo, PRIMARY);
1101
1102         // setup params
1103         ckmc_param_list_h handle = NULL;
1104         assert_positive(ckmc_generate_new_params, algo.type, &handle);
1105         ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
1106         setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
1107
1108         assert_crypto_invalid_param(apiDecrypt,
1109                                     params.get(),
1110                                     aliases.prv.c_str(),
1111                                     nullptr,
1112                                     encrypted,
1113                                     &decrypted);
1114     });
1115 }
1116
1117 RUNNER_TEST_MULTIPLE(TED_0140_decrypt_no_output_buffer, SyncEnv, AsyncEnv)
1118 {
1119     testAllAlgorithms([](const Algo& algo){
1120         // prepare buffers
1121         ckmc_raw_buffer_s** decrypted = nullptr;
1122
1123         // encrypt
1124         auto ret = encrypt(algo, PLAIN_DATA);
1125
1126         assert_crypto_invalid_param(apiDecrypt,
1127                                     ret.params.get(),
1128                                     ret.prvKey.c_str(),
1129                                     nullptr,
1130                                     *ret.encrypted.get(),
1131                                     decrypted);
1132     });
1133 }
1134
1135 RUNNER_TEST_MULTIPLE(TED_0200_encrypt_decrypt_different_keys, SyncEnv, AsyncEnv)
1136 {
1137     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_GCM, 128}, false);
1138     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_GCM, 192}, false);
1139     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_GCM, 256}, false);
1140     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_CTR, 128}, true);
1141     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_CTR, 192}, true);
1142     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_CTR, 256}, true);
1143     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_CFB, 128}, true);
1144     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_CFB, 192}, true);
1145     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_CFB, 256}, true);
1146     testEncryptDecryptDifferentKeys({CKMC_ALGO_RSA_OAEP, 1024}, false);
1147     testEncryptDecryptDifferentKeys({CKMC_ALGO_RSA_OAEP, 2048}, false);
1148     testEncryptDecryptDifferentKeys({CKMC_ALGO_RSA_OAEP, 4096}, false);
1149 }
1150
1151 RUNNER_TEST_MULTIPLE(TED_0300_encrypt_decrypt, SyncEnv, AsyncEnv)
1152 {
1153     testAllAlgorithms([](const Algo& algo){
1154         // prepare buffers
1155         ckmc_raw_buffer_s* decrypted = nullptr;
1156
1157         // encrypt
1158         auto ret = encrypt(algo, PLAIN_DATA);
1159
1160         assert_crypto_positive(apiDecrypt,
1161                                ret.params.get(),
1162                                ret.prvKey.c_str(),
1163                                nullptr,
1164                                *ret.encrypted.get(),
1165                                &decrypted);
1166         RawBufferPtr tmp = create_raw_buffer(decrypted);
1167
1168         assert_buffers_equal(*PLAIN_DATA.get(), *decrypted);
1169     });
1170 }
1171
1172 RUNNER_TEST_MULTIPLE(TED_0310_encrypt_decrypt_password, SyncEnv, AsyncEnv)
1173 {
1174     testAllAlgorithms([](const Algo& algo){
1175         // prepare buffers
1176         ckmc_raw_buffer_s* decrypted = nullptr;
1177
1178         // encrypt
1179         auto ret = encrypt(algo, PLAIN_DATA, PASSWORD);
1180
1181         // wrong password
1182         assert_crypto_result(EncryptionError::AUTH_FAILED,
1183                              apiDecrypt,
1184                              ret.params.get(),
1185                              ret.prvKey.c_str(),
1186                              "wrong-password",
1187                              *ret.encrypted.get(),
1188                              &decrypted);
1189
1190         // correct password
1191         assert_crypto_positive(apiDecrypt,
1192                                ret.params.get(),
1193                                ret.prvKey.c_str(),
1194                                PASSWORD,
1195                                *ret.encrypted.get(),
1196                                &decrypted);
1197         RawBufferPtr tmp = create_raw_buffer(decrypted); // guarantees deletion
1198
1199         assert_buffers_equal(*PLAIN_DATA.get(), *decrypted);
1200     });
1201 }
1202
1203 // long test split into smaller ones
1204 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CBC_128, SyncEnv, AsyncEnv)
1205 {
1206     testEncryptDecryptBigData({CKMC_ALGO_AES_CBC, 128});
1207 }
1208
1209 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CBC_192, SyncEnv, AsyncEnv)
1210 {
1211     testEncryptDecryptBigData({CKMC_ALGO_AES_CBC, 192});
1212 }
1213
1214 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CBC_256, SyncEnv, AsyncEnv)
1215 {
1216     testEncryptDecryptBigData({CKMC_ALGO_AES_CBC, 256});
1217 }
1218
1219 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_GCM_128, SyncEnv, AsyncEnv)
1220 {
1221     testEncryptDecryptBigData({CKMC_ALGO_AES_GCM, 128});
1222 }
1223
1224 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_GCM_192, SyncEnv, AsyncEnv)
1225 {
1226     testEncryptDecryptBigData({CKMC_ALGO_AES_GCM, 192});
1227 }
1228
1229 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_GCM_256, SyncEnv, AsyncEnv)
1230 {
1231     testEncryptDecryptBigData({CKMC_ALGO_AES_GCM, 256});
1232 }
1233
1234 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CTR_128, SyncEnv, AsyncEnv)
1235 {
1236     testEncryptDecryptBigData({CKMC_ALGO_AES_CTR, 128});
1237 }
1238
1239 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CTR_192, SyncEnv, AsyncEnv)
1240 {
1241     testEncryptDecryptBigData({CKMC_ALGO_AES_CTR, 192});
1242 }
1243
1244 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CTR_256, SyncEnv, AsyncEnv)
1245 {
1246     testEncryptDecryptBigData({CKMC_ALGO_AES_CTR, 256});
1247 }
1248
1249 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CFB_128, SyncEnv, AsyncEnv)
1250 {
1251     testEncryptDecryptBigData({CKMC_ALGO_AES_CFB, 128});
1252 }
1253
1254 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CFB_192, SyncEnv, AsyncEnv)
1255 {
1256     testEncryptDecryptBigData({CKMC_ALGO_AES_CFB, 192});
1257 }
1258
1259 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CFB_256, SyncEnv, AsyncEnv)
1260 {
1261     testEncryptDecryptBigData({CKMC_ALGO_AES_CFB, 256});
1262 }
1263
1264 /////////////////////////////////////////
1265 // Algorithm specific tests
1266 /////////////////////////////////////////
1267
1268 RUNNER_TEST_MULTIPLE(TED_1005_no_iv_enc, SyncEnv, AsyncEnv)
1269 {
1270     testNoIvEnc({CKMC_ALGO_AES_CTR, 128});
1271     testNoIvEnc({CKMC_ALGO_AES_CTR, 192});
1272     testNoIvEnc({CKMC_ALGO_AES_CTR, 256});
1273     testNoIvEnc({CKMC_ALGO_AES_CBC, 128});
1274     testNoIvEnc({CKMC_ALGO_AES_CBC, 192});
1275     testNoIvEnc({CKMC_ALGO_AES_CBC, 256});
1276     testNoIvEnc({CKMC_ALGO_AES_CFB, 128});
1277     testNoIvEnc({CKMC_ALGO_AES_CFB, 192});
1278     testNoIvEnc({CKMC_ALGO_AES_CFB, 256});
1279     testNoIvEnc({CKMC_ALGO_AES_GCM, 128});
1280     testNoIvEnc({CKMC_ALGO_AES_GCM, 192});
1281     testNoIvEnc({CKMC_ALGO_AES_GCM, 256});
1282 }
1283
1284 RUNNER_TEST_MULTIPLE(TED_1010_invalid_iv_enc, SyncEnv, AsyncEnv)
1285 {
1286     testInvalidIvEnc({CKMC_ALGO_AES_CTR, 128});
1287     testInvalidIvEnc({CKMC_ALGO_AES_CTR, 192});
1288     testInvalidIvEnc({CKMC_ALGO_AES_CTR, 256});
1289     testInvalidIvEnc({CKMC_ALGO_AES_CBC, 128});
1290     testInvalidIvEnc({CKMC_ALGO_AES_CBC, 192});
1291     testInvalidIvEnc({CKMC_ALGO_AES_CBC, 256});
1292     testInvalidIvEnc({CKMC_ALGO_AES_CFB, 128});
1293     testInvalidIvEnc({CKMC_ALGO_AES_CFB, 192});
1294     testInvalidIvEnc({CKMC_ALGO_AES_CFB, 256});
1295 }
1296
1297 RUNNER_TEST_MULTIPLE(TED_1015_no_iv_dec, SyncEnv, AsyncEnv)
1298 {
1299     testNoIvDec({CKMC_ALGO_AES_CTR, 128});
1300     testNoIvDec({CKMC_ALGO_AES_CTR, 192});
1301     testNoIvDec({CKMC_ALGO_AES_CTR, 256});
1302     testNoIvDec({CKMC_ALGO_AES_CBC, 128});
1303     testNoIvDec({CKMC_ALGO_AES_CBC, 192});
1304     testNoIvDec({CKMC_ALGO_AES_CBC, 256});
1305     testNoIvDec({CKMC_ALGO_AES_CFB, 128});
1306     testNoIvDec({CKMC_ALGO_AES_CFB, 192});
1307     testNoIvDec({CKMC_ALGO_AES_CFB, 256});
1308     testNoIvDec({CKMC_ALGO_AES_GCM, 128});
1309     testNoIvDec({CKMC_ALGO_AES_GCM, 192});
1310     testNoIvDec({CKMC_ALGO_AES_GCM, 256});
1311 }
1312
1313 RUNNER_TEST_MULTIPLE(TED_1020_invalid_iv_dec, SyncEnv, AsyncEnv)
1314 {
1315     testInvalidIvDec({CKMC_ALGO_AES_CTR, 128});
1316     testInvalidIvDec({CKMC_ALGO_AES_CTR, 192});
1317     testInvalidIvDec({CKMC_ALGO_AES_CTR, 256});
1318     testInvalidIvDec({CKMC_ALGO_AES_CBC, 128});
1319     testInvalidIvDec({CKMC_ALGO_AES_CBC, 192});
1320     testInvalidIvDec({CKMC_ALGO_AES_CBC, 256});
1321     testInvalidIvDec({CKMC_ALGO_AES_CFB, 128});
1322     testInvalidIvDec({CKMC_ALGO_AES_CFB, 192});
1323     testInvalidIvDec({CKMC_ALGO_AES_CFB, 256});
1324 }
1325
1326 RUNNER_TEST_MULTIPLE(TED_1050_data_integrity, SyncEnv, AsyncEnv)
1327 {
1328     testIntegrity({CKMC_ALGO_AES_CTR, 128});
1329     testIntegrity({CKMC_ALGO_AES_CTR, 192});
1330     testIntegrity({CKMC_ALGO_AES_CTR, 256});
1331     testIntegrity({CKMC_ALGO_AES_CBC, 128});
1332     testIntegrity({CKMC_ALGO_AES_CBC, 192});
1333     testIntegrity({CKMC_ALGO_AES_CBC, 256});
1334     testIntegrity({CKMC_ALGO_AES_CFB, 128});
1335     testIntegrity({CKMC_ALGO_AES_CFB, 192});
1336     testIntegrity({CKMC_ALGO_AES_CFB, 256});
1337 }
1338
1339 RUNNER_TEST_MULTIPLE(TED_1100_ctr_encryption_invalid_length, SyncEnv, AsyncEnv)
1340 {
1341     testCtrEncryptionInvalidLength({CKMC_ALGO_AES_CTR, 128});
1342     testCtrEncryptionInvalidLength({CKMC_ALGO_AES_CTR, 192});
1343     testCtrEncryptionInvalidLength({CKMC_ALGO_AES_CTR, 256});
1344 }
1345
1346 RUNNER_TEST_MULTIPLE(TED_1105_ctr_encryption_valid_length, SyncEnv, AsyncEnv)
1347 {
1348     RUNNER_IGNORED_MSG("Openssl supports only 128-bit AES CTR length");
1349     testCtrEncryptionValidLength({CKMC_ALGO_AES_CTR, 128});
1350     testCtrEncryptionValidLength({CKMC_ALGO_AES_CTR, 192});
1351     testCtrEncryptionValidLength({CKMC_ALGO_AES_CTR, 256});
1352 }
1353
1354 RUNNER_TEST_MULTIPLE(TED_1110_ctr_decryption_invalid_length, SyncEnv, AsyncEnv)
1355 {
1356     testCtrDecryptionInvalidLength({CKMC_ALGO_AES_CTR, 128});
1357     testCtrDecryptionInvalidLength({CKMC_ALGO_AES_CTR, 192});
1358     testCtrDecryptionInvalidLength({CKMC_ALGO_AES_CTR, 256});
1359 }
1360
1361 RUNNER_TEST_MULTIPLE(TED_1115_ctr_decryption_valid_length, SyncEnv, AsyncEnv)
1362 {
1363     RUNNER_IGNORED_MSG("Openssl supports only 128-bit AES CTR length");
1364     testCtrDecryptionValidLength({CKMC_ALGO_AES_CTR, 128});
1365     testCtrDecryptionValidLength({CKMC_ALGO_AES_CTR, 192});
1366     testCtrDecryptionValidLength({CKMC_ALGO_AES_CTR, 256});
1367 }
1368
1369 RUNNER_TEST_MULTIPLE(TED_1200_gcm_encryption_tag_len, SyncEnv, AsyncEnv)
1370 {
1371     testGcmEncryptionTagLen({CKMC_ALGO_AES_GCM, 128});
1372     testGcmEncryptionTagLen({CKMC_ALGO_AES_GCM, 192});
1373     testGcmEncryptionTagLen({CKMC_ALGO_AES_GCM, 256});
1374 }
1375
1376 RUNNER_TEST_MULTIPLE(TED_1210_gcm_decryption_tag_len, SyncEnv, AsyncEnv)
1377 {
1378     testGcmDecryptionTagLen({CKMC_ALGO_AES_GCM, 128});
1379     testGcmDecryptionTagLen({CKMC_ALGO_AES_GCM, 192});
1380     testGcmDecryptionTagLen({CKMC_ALGO_AES_GCM, 256});
1381 }
1382
1383 RUNNER_TEST_MULTIPLE(TED_1230_gcm_wrong_tag, SyncEnv, AsyncEnv)
1384 {
1385     testGcmWrongTag({CKMC_ALGO_AES_GCM, 128});
1386     testGcmWrongTag({CKMC_ALGO_AES_GCM, 192});
1387     testGcmWrongTag({CKMC_ALGO_AES_GCM, 256});
1388 }
1389
1390 RUNNER_TEST_MULTIPLE(TED_1240_gcm_different_iv_sizes, SyncEnv, AsyncEnv)
1391 {
1392     testGcmDifferentIvSizes({CKMC_ALGO_AES_GCM, 128});
1393     testGcmDifferentIvSizes({CKMC_ALGO_AES_GCM, 192});
1394     testGcmDifferentIvSizes({CKMC_ALGO_AES_GCM, 256});
1395 }
1396
1397 RUNNER_TEST_MULTIPLE(TED_1250_gcm_aad, SyncEnv, AsyncEnv)
1398 {
1399     encryptionWithCustomData({CKMC_ALGO_AES_GCM, 128}, CKMC_PARAM_ED_AAD);
1400     encryptionWithCustomData({CKMC_ALGO_AES_GCM, 192}, CKMC_PARAM_ED_AAD);
1401     encryptionWithCustomData({CKMC_ALGO_AES_GCM, 256}, CKMC_PARAM_ED_AAD);
1402 }
1403
1404 RUNNER_TEST_MULTIPLE(TED_1300_rsa_label, SyncEnv, AsyncEnv)
1405 {
1406     RUNNER_IGNORED_MSG("RSA-OAEP labels are not supported in openssl");
1407     encryptionWithCustomData({CKMC_ALGO_RSA_OAEP, 1024}, CKMC_PARAM_ED_LABEL);
1408     encryptionWithCustomData({CKMC_ALGO_RSA_OAEP, 2048}, CKMC_PARAM_ED_LABEL);
1409     encryptionWithCustomData({CKMC_ALGO_RSA_OAEP, 4096}, CKMC_PARAM_ED_LABEL);
1410 }
1411
1412 RUNNER_TEST_MULTIPLE(TED_1330_rsa_longest_data, SyncEnv, AsyncEnv)
1413 {
1414     testRsaLongestData({CKMC_ALGO_RSA_OAEP, 1024}, 86);
1415     testRsaLongestData({CKMC_ALGO_RSA_OAEP, 2048}, 214);
1416     testRsaLongestData({CKMC_ALGO_RSA_OAEP, 4096}, 470);
1417 }
1418
1419 RUNNER_TEST_MULTIPLE(TED_1350_rsa_data_too_long, SyncEnv, AsyncEnv)
1420 {
1421     testRsaDataTooLong({CKMC_ALGO_RSA_OAEP, 1024}, 87);
1422     testRsaDataTooLong({CKMC_ALGO_RSA_OAEP, 2048}, 215);
1423     testRsaDataTooLong({CKMC_ALGO_RSA_OAEP, 4096}, 471);
1424 }
1425
1426 /////////////////////////////////////////
1427 // Asynchronous only tests
1428 /////////////////////////////////////////
1429 RUNNER_TEST(TED_2000_enc_no_observer_async, AsyncEnv)
1430 {
1431     testAllAlgorithms([](const Algo& algo){
1432         // prepare buffers
1433         RawBuffer plain = createRandomBuffer(BUF_LEN);
1434
1435         // keys
1436         KeyAliasPair aliases = getKey(algo, PRIMARY);
1437
1438         // params
1439         ckmc_param_list_h handle = NULL;
1440         assert_positive(ckmc_generate_new_params, algo.type, &handle);
1441         ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
1442         setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
1443
1444         // encrypt
1445         test_no_observer(&ManagerAsync::encrypt,
1446                          *reinterpret_cast<CryptoAlgorithm*>(params.get()),
1447                          aliases.pub,
1448                          Password(),
1449                          plain);
1450     });
1451 }
1452
1453 RUNNER_TEST(TED_2010_dec_no_observer_async, AsyncEnv)
1454 {
1455     testAllAlgorithms([](const Algo& algo){
1456         // encrypt
1457         auto ret = encrypt(algo, PLAIN_DATA);
1458         RawBuffer encrypted(ret.encrypted->data, ret.encrypted->data + ret.encrypted->size);
1459
1460         // decrypt
1461         test_no_observer(&ManagerAsync::decrypt,
1462                          *reinterpret_cast<CryptoAlgorithm*>(ret.params.get()),
1463                          ret.prvKey,
1464                          Password(),
1465                          encrypted);
1466     });
1467 }
1468
1469 /////////////////////////////////////////
1470 // Mulithreaded test for synchronous API
1471 /////////////////////////////////////////
1472 RUNNER_TEST(TED_3000_muliple_threads, SyncEnv)
1473 {
1474     std::vector<std::thread> threads;
1475     threads.reserve(10);
1476     for(unsigned i = 0; i < 10;++i)
1477         threads.emplace_back([]{ testEncryptDecryptBigData({CKMC_ALGO_AES_CBC, 256}); });
1478     for (auto& thread : threads)
1479         thread.join();
1480 }