a29c452bfc3c8634c9a5aaea0fc20d9c26447aaa
[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 struct EncryptionResult
292 {
293     RawBufferPtr encrypted;
294     ParamListPtr params;
295     Alias prvKey;
296     Alias pubKey;
297 };
298
299 EncryptionResult encrypt(const Algo& algo,
300                          const RawBufferPtr& plain,
301                          const char* pass = nullptr)
302 {
303     EncryptionResult ret;
304     ckmc_raw_buffer_s* encrypted = nullptr;
305     KeyAliasPair aliases = getKey(algo, pass == nullptr ? PRIMARY : PASSWORD_PROTECTED);
306
307     ckmc_param_list_h handle = NULL;
308     assert_positive(ckmc_generate_new_params, algo.type, &handle);
309     ret.params = ParamListPtr(handle, ckmc_param_list_free);
310     setParam(ret.params, CKMC_PARAM_ED_IV, DEFAULT_IV);
311
312     assert_crypto_positive(apiEncrypt,
313                            ret.params.get(),
314                            aliases.pub.c_str(),
315                            pass,
316                            *plain.get(),
317                            &encrypted);
318
319     ret.encrypted = create_raw_buffer(encrypted);
320     ret.prvKey = aliases.prv;
321     ret.pubKey = aliases.pub;
322     return ret;
323 }
324
325 void testAllAlgorithms(
326         const std::function<void(const Algo& algo)>& test)
327 {
328     test( { CKMC_ALGO_AES_CBC, 128 });
329     test( { CKMC_ALGO_AES_CBC, 192 });
330     test( { CKMC_ALGO_AES_CBC, 256 });
331     test( { CKMC_ALGO_AES_GCM, 128 });
332     test( { CKMC_ALGO_AES_GCM, 192 });
333     test( { CKMC_ALGO_AES_GCM, 256 });
334     test( { CKMC_ALGO_AES_CTR, 128 });
335     test( { CKMC_ALGO_AES_CTR, 192 });
336     test( { CKMC_ALGO_AES_CTR, 256 });
337     test( { CKMC_ALGO_AES_CFB, 128 });
338     test( { CKMC_ALGO_AES_CFB, 192 });
339     test( { CKMC_ALGO_AES_CFB, 256 });
340     test( { CKMC_ALGO_RSA_OAEP, 1024 });
341     test( { CKMC_ALGO_RSA_OAEP, 2048 });
342     test( { CKMC_ALGO_RSA_OAEP, 4096 });
343 }
344
345 void testNoIvEnc(const Algo& algo)
346 {
347     // prepare buffers
348     ckmc_raw_buffer_s* encrypted = nullptr;
349
350     // add key
351     KeyAliasPair aliases = getKey(algo, PRIMARY);
352
353     // param list with algo type only
354     ParamListPtr params = createParamListPtr();
355     setParam(params, CKMC_PARAM_ALGO_TYPE, algo.type);
356     assert_crypto_invalid_param(apiEncrypt,
357                                 params.get(),
358                                 aliases.pub.c_str(),
359                                 nullptr,
360                                 *PLAIN_DATA.get(),
361                                 &encrypted);
362 }
363
364 void testNoIvDec(const Algo& algo)
365 {
366     // prepare buffers
367     ckmc_raw_buffer_s* decrypted = nullptr;
368
369     // encrypt;
370     auto ret = encrypt(algo, PLAIN_DATA);
371
372     // param list with algo type only
373     ParamListPtr params = createParamListPtr();
374     setParam(params, CKMC_PARAM_ALGO_TYPE, algo.type);
375     assert_crypto_invalid_param(apiDecrypt,
376                                 params.get(),
377                                 ret.prvKey.c_str(),
378                                 nullptr,
379                                 *ret.encrypted.get(),
380                                 &decrypted);
381 }
382
383 void testInvalidIvEnc(const Algo& algo)
384 {
385     // prepare buffers
386     ckmc_raw_buffer_s* encryptedTmp = nullptr;
387
388     // add key
389     KeyAliasPair aliases = getKey(algo, PRIMARY);
390
391     // setup params
392     ckmc_param_list_h handle = NULL;
393     assert_positive(ckmc_generate_new_params, algo.type, &handle);
394     ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
395
396     // invalid encryption
397     auto test = [&](){
398         assert_crypto_invalid_param(apiEncrypt,
399                                     params.get(),
400                                     aliases.pub.c_str(),
401                                     nullptr,
402                                     *PLAIN_DATA.get(),
403                                     &encryptedTmp);
404         ckmc_buffer_free(encryptedTmp);
405         encryptedTmp = nullptr;
406     };
407     // invalid iv size
408     setParam(params, CKMC_PARAM_ED_IV, IV15);
409     test();
410     setParam(params, CKMC_PARAM_ED_IV, IV17);
411     test();
412 };
413
414 void testInvalidIvDec(const Algo& algo)
415 {
416     // prepare buffers
417     ckmc_raw_buffer_s* decrypted = nullptr;
418
419     // valid encryption
420     auto ret = encrypt(algo, PLAIN_DATA);
421
422     // decryption
423     auto test2 = [&](){
424         assert_crypto_invalid_param(apiDecrypt,
425                                     ret.params.get(),
426                                     ret.prvKey.c_str(),
427                                     nullptr,
428                                     *ret.encrypted.get(),
429                                     &decrypted);
430         ckmc_buffer_free(decrypted);
431         decrypted = nullptr;
432     };
433
434     // invalid iv size
435     setParam(ret.params, CKMC_PARAM_ED_IV, IV15);
436     test2();
437     setParam(ret.params, CKMC_PARAM_ED_IV, IV17);
438     test2();
439 };
440
441 void encryptionWithCustomData(const Algo& algo, ckmc_param_name_e name)
442 {
443     // prepare buffers
444     ckmc_raw_buffer_s* encrypted = nullptr;
445     ckmc_raw_buffer_s* decrypted = nullptr;
446
447     // add key
448     KeyAliasPair aliases = getKey(algo, PRIMARY);
449
450     // setup params
451     ckmc_param_list_h handle = NULL;
452     assert_positive(ckmc_generate_new_params, algo.type, &handle);
453     ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
454
455     setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
456
457     // set AAD
458     setParam(params, name, AAD64);
459
460     // encrypt
461     assert_crypto_positive(apiEncrypt,
462                            params.get(),
463                            aliases.pub.c_str(),
464                            nullptr,
465                            *PLAIN_DATA.get(),
466                            &encrypted);
467     RawBufferPtr tmpEnc = create_raw_buffer(encrypted);
468
469     // decrypt
470     assert_crypto_positive(apiDecrypt,
471                            params.get(),
472                            aliases.prv.c_str(),
473                            nullptr,
474                            *tmpEnc.get(),
475                            &decrypted);
476     RawBufferPtr tmpDec = create_raw_buffer(decrypted);
477
478     // check
479     assert_buffers_equal(PLAIN_DATA.get(), tmpDec.get());
480     tmpDec.reset();
481     decrypted = nullptr;
482
483     // set wrong AAD
484     setParam(params, name, AAD32);
485
486     // decrypt
487     assert_crypto_result(EncryptionError::INVALID_PARAM,
488                          apiDecrypt,
489                          params.get(),
490                          aliases.prv.c_str(),
491                          nullptr,
492                          *tmpEnc.get(),
493                          &decrypted);
494 }
495
496 void testGcmIvSize(ckmc_raw_buffer_s* iv,
497                    const KeyAliasPair& aliases,
498                    EncryptionError error = EncryptionError::SUCCESS)
499 {
500     // prepare buffers
501     RawBufferPtr encrypted;
502     RawBufferPtr decrypted;
503     ckmc_raw_buffer_s* encryptedTmp = nullptr;
504     ckmc_raw_buffer_s* decryptedTmp = nullptr;
505
506     // setup params
507     ckmc_param_list_h handle = NULL;
508     assert_positive(ckmc_generate_new_params, CKMC_ALGO_AES_GCM, &handle);
509     ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
510     setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
511     setParam(params, CKMC_PARAM_ED_IV, iv);
512
513     // encryption
514     assert_crypto_result(error,
515                          apiEncrypt,
516                          params.get(),
517                          aliases.pub.c_str(),
518                          nullptr,
519                          *PLAIN_DATA.get(),
520                          &encryptedTmp);
521
522     if(error != EncryptionError::SUCCESS)
523         return;
524     encrypted = create_raw_buffer(encryptedTmp);
525
526     // decryption
527     assert_crypto_positive(apiDecrypt,
528                            params.get(),
529                            aliases.prv.c_str(),
530                            nullptr,
531                            *encrypted.get(),
532                            &decryptedTmp);
533     decrypted = create_raw_buffer(decryptedTmp);
534
535     assert_buffers_equal(PLAIN_DATA.get(), decrypted.get());
536 }
537
538 void testIntegrity(const Algo& algo)
539 {
540     // prepare buffers
541     ckmc_raw_buffer_s* decrypted = nullptr;
542
543     // encrypt
544     auto ret = encrypt(algo, PLAIN_DATA);
545
546     // break the encrypted data
547     ret.encrypted->data[BUF_LEN/2]++;
548
549     // no data integrity check
550     assert_crypto_positive(apiDecrypt,
551                            ret.params.get(),
552                            ret.prvKey.c_str(),
553                            nullptr,
554                            *ret.encrypted.get(),
555                            &decrypted);
556
557     RawBufferPtr tmp = create_raw_buffer(decrypted);
558     assert_buffers_equal(PLAIN_DATA.get(), decrypted, false);
559 }
560
561 void testCtrEncryptionInvalidLength(const Algo& algo)
562 {
563     // prepare buffers
564     ckmc_raw_buffer_s* encryptedTmp = nullptr;
565
566     // add AES CTR key
567     KeyAliasPair aliases = getKey(algo, PRIMARY);
568
569     // setup params
570     ckmc_param_list_h handle = NULL;
571     assert_positive(ckmc_generate_new_params, algo.type, &handle);
572     ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
573     setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
574
575     // encryption
576     auto test = [&](){
577         assert_crypto_invalid_param(apiEncrypt,
578                                     params.get(),
579                                     aliases.pub.c_str(),
580                                     nullptr,
581                                     *PLAIN_DATA.get(),
582                                     &encryptedTmp);
583         ckmc_buffer_free(encryptedTmp);
584         encryptedTmp = nullptr;
585     };
586     // invalid counter size
587     setParam(params, CKMC_PARAM_ED_CTR_LEN, 0ULL);
588     test();
589     setParam(params, CKMC_PARAM_ED_CTR_LEN, CTR_DEFAULT_LEN+1);
590     test();
591 }
592
593 void testCtrEncryptionValidLength(const Algo& algo)
594 {
595     // prepare buffers
596     ckmc_raw_buffer_s* encryptedTmp = nullptr;
597
598     // add AES CTR key
599     KeyAliasPair aliases = getKey(algo, PRIMARY);
600
601     // setup params
602     ckmc_param_list_h handle = NULL;
603     assert_positive(ckmc_generate_new_params, algo.type, &handle);
604     ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
605     setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
606
607     // encryption
608     auto test = [&](){
609         assert_crypto_positive(apiEncrypt,
610                                params.get(),
611                                aliases.pub.c_str(),
612                                nullptr,
613                                *PLAIN_DATA.get(),
614                                &encryptedTmp);
615         ckmc_buffer_free(encryptedTmp);
616         encryptedTmp = nullptr;
617     };
618     // valid counter sizez
619     setParam(params, CKMC_PARAM_ED_CTR_LEN, 1);
620     test();
621     setParam(params, CKMC_PARAM_ED_CTR_LEN, 4);
622     test();
623     setParam(params, CKMC_PARAM_ED_CTR_LEN, CTR_DEFAULT_LEN-1);
624     test();
625     setParam(params, CKMC_PARAM_ED_CTR_LEN, CTR_DEFAULT_LEN);
626     test();
627 }
628
629 void testCtrDecryptionInvalidLength(const Algo& algo)
630 {
631     // prepare buffers
632     ckmc_raw_buffer_s* decrypted = nullptr;
633
634     // add AES CTR key & encrypt
635     auto ret = encrypt(algo, PLAIN_DATA);
636
637     // decryption
638     auto test = [&](){
639         assert_crypto_invalid_param(apiDecrypt,
640                                     ret.params.get(),
641                                     ret.prvKey.c_str(),
642                                     nullptr,
643                                     *ret.encrypted.get(),
644                                     &decrypted);
645         ckmc_buffer_free(decrypted);
646         decrypted = nullptr;
647     };
648     // invalid counter size
649     setParam(ret.params, CKMC_PARAM_ED_CTR_LEN, 0ULL);
650     test();
651     setParam(ret.params, CKMC_PARAM_ED_CTR_LEN, CTR_DEFAULT_LEN+1);
652     test();
653 }
654
655 void testCtrDecryptionValidLength(const Algo& algo)
656 {
657     // prepare buffers
658     ckmc_raw_buffer_s* decrypted = nullptr;
659
660     // add AES CTR key & encrypt
661     auto ret = encrypt(algo, PLAIN_DATA);
662
663     // decryption
664     auto test = [&](){
665         assert_crypto_positive(apiDecrypt,
666                                ret.params.get(),
667                                ret.prvKey.c_str(),
668                                nullptr,
669                                *ret.encrypted.get(),
670                                &decrypted);
671         ckmc_buffer_free(decrypted);
672         RawBufferPtr tmp = create_raw_buffer(decrypted);
673         assert_buffers_equal(PLAIN_DATA.get(), decrypted);
674     };
675     // invalid counter size
676     setParam(ret.params, CKMC_PARAM_ED_CTR_LEN, 1);
677     test();
678     setParam(ret.params, CKMC_PARAM_ED_CTR_LEN, 4);
679     test();
680     setParam(ret.params, CKMC_PARAM_ED_CTR_LEN, CTR_DEFAULT_LEN-1);
681     test();
682     setParam(ret.params, CKMC_PARAM_ED_CTR_LEN, CTR_DEFAULT_LEN);
683     test();
684 }
685
686 void testGcmEncryptionTagLen(const Algo& algo)
687 {
688     // prepare buffers
689     ckmc_raw_buffer_s* encryptedTmp = nullptr;
690
691     // add AES GCM key
692     KeyAliasPair aliases = getKey(algo, PRIMARY);
693
694     // setup params
695     ckmc_param_list_h handle = NULL;
696     assert_positive(ckmc_generate_new_params, algo.type, &handle);
697     ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
698     setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
699
700     std::vector<TagTest> testData = {
701             // illegal tag lengths
702             { -1,   EncryptionError::INVALID_PARAM },
703             { 0,    EncryptionError::INVALID_PARAM },
704             { 16,   EncryptionError::INVALID_PARAM },
705             { 48,   EncryptionError::INVALID_PARAM },
706             { 72,   EncryptionError::INVALID_PARAM },
707             { 100,  EncryptionError::INVALID_PARAM },
708             { 108,  EncryptionError::INVALID_PARAM },
709             { 116,  EncryptionError::INVALID_PARAM },
710             { 124,  EncryptionError::INVALID_PARAM },
711             { 256,  EncryptionError::INVALID_PARAM },
712 #ifdef TZ_BACKEND
713             { 32,   EncryptionError::INVALID_PARAM },
714             { 64,   EncryptionError::INVALID_PARAM },
715             // legal tag lengths
716 #else
717             // legal tag lengths
718             { 32,   EncryptionError::SUCCESS },
719             { 64,   EncryptionError::SUCCESS },
720 #endif
721
722             { 96,   EncryptionError::SUCCESS },
723             { 104,  EncryptionError::SUCCESS },
724             { 112,  EncryptionError::SUCCESS },
725             { 120,  EncryptionError::SUCCESS },
726             { 128,  EncryptionError::SUCCESS },
727     };
728
729     // encryption
730     for(const auto& it : testData)
731     {
732         setParam(params, CKMC_PARAM_ED_TAG_LEN, it.tagLen);
733         assert_crypto_result(it.expected,
734                              apiEncrypt,
735                              params.get(),
736                              aliases.pub.c_str(),
737                              nullptr,
738                              *PLAIN_DATA.get(),
739                              &encryptedTmp);
740         ckmc_buffer_free(encryptedTmp);
741         encryptedTmp = nullptr;
742     }
743 }
744
745 void testGcmDecryptionTagLen(const Algo& algo)
746 {
747     // prepare buffers
748     ckmc_raw_buffer_s* decrypted = nullptr;
749
750     // add AES GCM key & encrypt
751     auto ret = encrypt(algo, PLAIN_DATA);
752
753     std::vector<TagTest> testData = {
754             // illegal tag lengths
755             { -1,   EncryptionError::INVALID_PARAM },
756             { 0,    EncryptionError::INVALID_PARAM },
757             { 16,   EncryptionError::INVALID_PARAM },
758             { 48,   EncryptionError::INVALID_PARAM },
759             { 72,   EncryptionError::INVALID_PARAM },
760             { 100,  EncryptionError::INVALID_PARAM },
761             { 108,  EncryptionError::INVALID_PARAM },
762             { 116,  EncryptionError::INVALID_PARAM },
763             { 124,  EncryptionError::INVALID_PARAM },
764             { 256,  EncryptionError::INVALID_PARAM },
765             // legal tag lengths but different than the one used for encryption
766             { 32,   EncryptionError::INVALID_PARAM },
767             { 64,   EncryptionError::INVALID_PARAM },
768             { 96,   EncryptionError::INVALID_PARAM },
769             { 104,  EncryptionError::INVALID_PARAM },
770             { 112,  EncryptionError::INVALID_PARAM },
771             { 120,  EncryptionError::INVALID_PARAM },
772             // legal tag length that was actually used for encryption (default)
773             { 128,  EncryptionError::SUCCESS },
774     };
775
776     // decryption
777     for(const auto& it : testData)
778     {
779         setParam(ret.params, CKMC_PARAM_ED_TAG_LEN, it.tagLen);
780         assert_crypto_result(it.expected,
781                              apiDecrypt,
782                              ret.params.get(),
783                              ret.prvKey.c_str(),
784                              nullptr,
785                              *ret.encrypted.get(),
786                              &decrypted);
787         ckmc_buffer_free(decrypted);
788         decrypted = nullptr;
789     }
790 }
791
792 void testGcmWrongTag(const Algo& algo)
793 {
794     // prepare buffers
795     ckmc_raw_buffer_s* decrypted = nullptr;
796
797     // encrypt with AES GCM
798     auto ret = encrypt(algo, PLAIN_DATA);
799
800     // modify tag (last 16B of encrypted message)
801     ret.encrypted->data[ret.encrypted->size-1]++;
802
803     // EVP_CipherFinal fails because of an authentication error
804     assert_crypto_result(EncryptionError::INVALID_PARAM,
805                          apiDecrypt,
806                          ret.params.get(),
807                          ret.prvKey.c_str(),
808                          nullptr,
809                          *ret.encrypted.get(),
810                          &decrypted);
811 }
812
813 void testGcmDifferentIvSizes(const Algo& algo)
814 {
815     // add AES GCM key
816     KeyAliasPair aliases = getKey(algo, PRIMARY);
817
818     testGcmIvSize(IV11,  aliases, EncryptionError::SERVER_ERROR); // 12B is the smallest
819     testGcmIvSize(IV12,  aliases);
820     testGcmIvSize(IV17,  aliases);
821     testGcmIvSize(IV128, aliases);
822 }
823
824 void testEncryptDecryptBigData(const Algo& algo)
825 {
826     // prepare buffers
827     ckmc_raw_buffer_s* decrypted = nullptr;
828
829     // encrypt
830     auto ret = encrypt(algo, BIG_DATA);
831
832     assert_positive(apiDecrypt,
833                     ret.params.get(),
834                     ret.prvKey.c_str(),
835                     nullptr,
836                     *ret.encrypted.get(),
837                     &decrypted);
838     RawBufferPtr tmp = create_raw_buffer(decrypted);
839
840     assert_buffers_equal(BIG_DATA.get(), decrypted);
841 }
842
843 void testEncryptDecryptDifferentKeys(const Algo& algo, bool success)
844 {
845     // prepare buffers
846     ckmc_raw_buffer_s* decrypted = nullptr;
847
848     // encrypt
849     auto ret = encrypt(algo, PLAIN_DATA);
850
851     // get different keys
852     KeyAliasPair differentKeys = getKey(algo, PASSWORD_PROTECTED);
853
854     if (success) {
855         // some algorithms don't verify key validity
856         assert_crypto_positive(apiDecrypt,
857                                ret.params.get(),
858                                differentKeys.prv.c_str(),
859                                PASSWORD,
860                                *ret.encrypted.get(),
861                                &decrypted);
862         RawBufferPtr tmp = create_raw_buffer(decrypted);
863
864         assert_buffers_equal(PLAIN_DATA.get(), decrypted, false);
865     } else {
866         assert_crypto_result(EncryptionError::INVALID_PARAM,
867                              apiDecrypt,
868                              ret.params.get(),
869                              differentKeys.prv.c_str(),
870                              PASSWORD,
871                              *ret.encrypted.get(),
872                              &decrypted);
873     }
874 }
875
876 void testRsaLongestData(const Algo& algo, size_t dataSize)
877 {
878     // prepare buffers
879     RawBufferPtr plain = create_raw_buffer(createRandomBufferCAPI(dataSize));
880     ckmc_raw_buffer_s* decrypted = nullptr;
881
882     // encrypt
883     auto ret = encrypt(algo, plain);
884
885     assert_crypto_positive(apiDecrypt,
886                            ret.params.get(),
887                            ret.prvKey.c_str(),
888                            nullptr,
889                            *ret.encrypted.get(),
890                            &decrypted);
891     RawBufferPtr tmp = create_raw_buffer(decrypted);
892
893     assert_buffers_equal(plain.get(), decrypted);
894 }
895
896 void testRsaDataTooLong(const Algo& algo, size_t dataSize)
897 {
898     // prepare buffers
899     RawBufferPtr plain = create_raw_buffer(createRandomBufferCAPI(dataSize));
900
901     // encrypt
902     EncryptionResult ret;
903     ckmc_raw_buffer_s* encrypted = nullptr;
904     KeyAliasPair aliases = getKey(algo, PRIMARY);
905
906     ckmc_param_list_h handle = NULL;
907     assert_positive(ckmc_generate_new_params, algo.type, &handle);
908     ret.params = ParamListPtr(handle, ckmc_param_list_free);
909     assert_crypto_result(EncryptionError::INVALID_PARAM,
910                          apiEncrypt,
911                          ret.params.get(),
912                          aliases.pub.c_str(),
913                          nullptr,
914                          *plain.get(),
915                          &encrypted);
916 }
917
918 } // namespace anonymous
919
920 RUNNER_TEST_GROUP_INIT_ENV(CKM_ENCRYPTION_DECRYPTION, EncGroupFixture);
921
922 /////////////////////////////////////////
923 // Generic encryption decryption tests
924 /////////////////////////////////////////
925
926 RUNNER_TEST_MULTIPLE(TED_0010_encrypt_invalid_param_list, SyncEnv, AsyncEnv)
927 {
928     testAllAlgorithms([](const Algo& algo){
929         // prepare buffers
930         ckmc_raw_buffer_s* encrypted = nullptr;
931
932         // add key
933         KeyAliasPair aliases = getKey(algo, PRIMARY);
934
935         // null param list
936         assert_crypto_invalid_param(apiEncrypt,
937                                     nullptr,
938                                     aliases.pub.c_str(),
939                                     nullptr,
940                                     *PLAIN_DATA.get(),
941                                     &encrypted);
942
943         // empty param list
944         ParamListPtr params = createParamListPtr();
945         assert_crypto_invalid_param(apiEncrypt,
946                                     params.get(),
947                                     aliases.pub.c_str(),
948                                     nullptr,
949                                     *PLAIN_DATA.get(),
950                                     &encrypted);
951     });
952 }
953
954 RUNNER_TEST_MULTIPLE(TED_0020_encrypt_missing_key, SyncEnv, AsyncEnv)
955 {
956     testAllAlgorithms([](const Algo& algo){
957         // prepare buffers
958         ckmc_raw_buffer_s* encrypted = nullptr;
959
960         // setup params
961         ckmc_param_list_h handle = NULL;
962         assert_positive(ckmc_generate_new_params, algo.type, &handle);
963         ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
964         setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
965
966         assert_crypto_result(EncryptionError::ALIAS_UNKNOWN,
967                              apiEncrypt,
968                              params.get(),
969                              "non-existing-key-alias",
970                              nullptr,
971                              *PLAIN_DATA.get(),
972                              &encrypted);
973     });
974 }
975
976 RUNNER_TEST_MULTIPLE(TED_0030_encrypt_no_plain_text, SyncEnv, AsyncEnv)
977 {
978     testAllAlgorithms([](const Algo& algo){
979         // prepare buffers
980         ckmc_raw_buffer_s plain = { nullptr, 0 };
981         ckmc_raw_buffer_s* encrypted = nullptr;
982
983         // add key
984         KeyAliasPair aliases = getKey(algo, PRIMARY);
985
986         // setup params
987         ckmc_param_list_h handle = NULL;
988         assert_positive(ckmc_generate_new_params, algo.type, &handle);
989         ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
990         setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
991
992         assert_crypto_invalid_param(apiEncrypt,
993                                     params.get(),
994                                     aliases.pub.c_str(),
995                                     nullptr,
996                                     plain,
997                                     &encrypted);
998     });
999 }
1000
1001 RUNNER_TEST_MULTIPLE(TED_0040_encrypt_no_output_buffer, SyncEnv, AsyncEnv)
1002 {
1003     testAllAlgorithms([](const Algo& algo){
1004         // prepare buffers
1005         ckmc_raw_buffer_s** encrypted = nullptr;
1006
1007         // add key
1008         KeyAliasPair aliases = getKey(algo, PRIMARY);
1009
1010         // setup params
1011         ckmc_param_list_h handle = NULL;
1012         assert_positive(ckmc_generate_new_params, algo.type, &handle);
1013         ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
1014         setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
1015
1016         assert_crypto_invalid_param(apiEncrypt,
1017                                     params.get(),
1018                                     aliases.pub.c_str(),
1019                                     nullptr,
1020                                     *PLAIN_DATA.get(),
1021                                     encrypted);
1022     });
1023 }
1024
1025 RUNNER_TEST_MULTIPLE(TED_0110_decrypt_invalid_param_list, SyncEnv, AsyncEnv)
1026 {
1027     testAllAlgorithms([](const Algo& algo){
1028         // prepare buffers
1029         ckmc_raw_buffer_s* decrypted = nullptr;
1030
1031         // encrypt;
1032         auto ret = encrypt(algo, PLAIN_DATA);
1033
1034         // null param list
1035         assert_crypto_invalid_param(apiDecrypt,
1036                                     nullptr,
1037                                     ret.prvKey.c_str(),
1038                                     nullptr,
1039                                     *ret.encrypted.get(),
1040                                     &decrypted);
1041
1042         // empty param list
1043         ParamListPtr params = createParamListPtr();
1044         assert_crypto_invalid_param(apiDecrypt,
1045                                     params.get(),
1046                                     ret.prvKey.c_str(),
1047                                     nullptr,
1048                                     *ret.encrypted.get(),
1049                                     &decrypted);
1050     });
1051 }
1052
1053 RUNNER_TEST_MULTIPLE(TED_0120_decrypt_missing_key, SyncEnv, AsyncEnv)
1054 {
1055     testAllAlgorithms([](const Algo& algo){
1056         // prepare buffers
1057         ckmc_raw_buffer_s* decrypted = nullptr;
1058
1059         // encrypt
1060         auto ret = encrypt(algo, PLAIN_DATA);
1061
1062         // try to decrypt
1063         assert_crypto_result(EncryptionError::ALIAS_UNKNOWN,
1064                              apiDecrypt,
1065                              ret.params.get(),
1066                              "non-existent-key",
1067                              nullptr,
1068                              *ret.encrypted.get(),
1069                              &decrypted);
1070     });
1071 }
1072
1073 RUNNER_TEST_MULTIPLE(TED_0130_decrypt_no_encrypted_text, SyncEnv, AsyncEnv)
1074 {
1075     testAllAlgorithms([](const Algo& algo){
1076         // prepare buffers
1077         ckmc_raw_buffer_s encrypted = { nullptr, 0 };
1078         ckmc_raw_buffer_s* decrypted = nullptr;
1079
1080         // add key
1081         KeyAliasPair aliases = getKey(algo, PRIMARY);
1082
1083         // setup params
1084         ckmc_param_list_h handle = NULL;
1085         assert_positive(ckmc_generate_new_params, algo.type, &handle);
1086         ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
1087         setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
1088
1089         assert_crypto_invalid_param(apiDecrypt,
1090                                     params.get(),
1091                                     aliases.prv.c_str(),
1092                                     nullptr,
1093                                     encrypted,
1094                                     &decrypted);
1095     });
1096 }
1097
1098 RUNNER_TEST_MULTIPLE(TED_0140_decrypt_no_output_buffer, SyncEnv, AsyncEnv)
1099 {
1100     testAllAlgorithms([](const Algo& algo){
1101         // prepare buffers
1102         ckmc_raw_buffer_s** decrypted = nullptr;
1103
1104         // encrypt
1105         auto ret = encrypt(algo, PLAIN_DATA);
1106
1107         assert_crypto_invalid_param(apiDecrypt,
1108                                     ret.params.get(),
1109                                     ret.prvKey.c_str(),
1110                                     nullptr,
1111                                     *ret.encrypted.get(),
1112                                     decrypted);
1113     });
1114 }
1115
1116 RUNNER_TEST_MULTIPLE(TED_0200_encrypt_decrypt_different_keys, SyncEnv, AsyncEnv)
1117 {
1118     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_GCM, 128}, false);
1119     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_GCM, 192}, false);
1120     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_GCM, 256}, false);
1121     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_CTR, 128}, true);
1122     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_CTR, 192}, true);
1123     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_CTR, 256}, true);
1124     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_CFB, 128}, true);
1125     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_CFB, 192}, true);
1126     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_CFB, 256}, true);
1127     testEncryptDecryptDifferentKeys({CKMC_ALGO_RSA_OAEP, 1024}, false);
1128     testEncryptDecryptDifferentKeys({CKMC_ALGO_RSA_OAEP, 2048}, false);
1129     testEncryptDecryptDifferentKeys({CKMC_ALGO_RSA_OAEP, 4096}, false);
1130 }
1131
1132 RUNNER_TEST_MULTIPLE(TED_0300_encrypt_decrypt, SyncEnv, AsyncEnv)
1133 {
1134     testAllAlgorithms([](const Algo& algo){
1135         // prepare buffers
1136         ckmc_raw_buffer_s* decrypted = nullptr;
1137
1138         // encrypt
1139         auto ret = encrypt(algo, PLAIN_DATA);
1140
1141         assert_crypto_positive(apiDecrypt,
1142                                ret.params.get(),
1143                                ret.prvKey.c_str(),
1144                                nullptr,
1145                                *ret.encrypted.get(),
1146                                &decrypted);
1147         RawBufferPtr tmp = create_raw_buffer(decrypted);
1148
1149         assert_buffers_equal(PLAIN_DATA.get(), decrypted);
1150     });
1151 }
1152
1153 RUNNER_TEST_MULTIPLE(TED_0310_encrypt_decrypt_password, SyncEnv, AsyncEnv)
1154 {
1155     testAllAlgorithms([](const Algo& algo){
1156         // prepare buffers
1157         ckmc_raw_buffer_s* decrypted = nullptr;
1158
1159         // encrypt
1160         auto ret = encrypt(algo, PLAIN_DATA, PASSWORD);
1161
1162         // wrong password
1163         assert_crypto_result(EncryptionError::AUTH_FAILED,
1164                              apiDecrypt,
1165                              ret.params.get(),
1166                              ret.prvKey.c_str(),
1167                              "wrong-password",
1168                              *ret.encrypted.get(),
1169                              &decrypted);
1170
1171         // correct password
1172         assert_crypto_positive(apiDecrypt,
1173                                ret.params.get(),
1174                                ret.prvKey.c_str(),
1175                                PASSWORD,
1176                                *ret.encrypted.get(),
1177                                &decrypted);
1178         RawBufferPtr tmp = create_raw_buffer(decrypted); // guarantees deletion
1179
1180         assert_buffers_equal(PLAIN_DATA.get(), decrypted);
1181     });
1182 }
1183
1184 // long test split into smaller ones
1185 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CBC_128, SyncEnv, AsyncEnv)
1186 {
1187     testEncryptDecryptBigData({CKMC_ALGO_AES_CBC, 128});
1188 }
1189
1190 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CBC_192, SyncEnv, AsyncEnv)
1191 {
1192     testEncryptDecryptBigData({CKMC_ALGO_AES_CBC, 192});
1193 }
1194
1195 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CBC_256, SyncEnv, AsyncEnv)
1196 {
1197     testEncryptDecryptBigData({CKMC_ALGO_AES_CBC, 256});
1198 }
1199
1200 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_GCM_128, SyncEnv, AsyncEnv)
1201 {
1202     testEncryptDecryptBigData({CKMC_ALGO_AES_GCM, 128});
1203 }
1204
1205 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_GCM_192, SyncEnv, AsyncEnv)
1206 {
1207     testEncryptDecryptBigData({CKMC_ALGO_AES_GCM, 192});
1208 }
1209
1210 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_GCM_256, SyncEnv, AsyncEnv)
1211 {
1212     testEncryptDecryptBigData({CKMC_ALGO_AES_GCM, 256});
1213 }
1214
1215 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CTR_128, SyncEnv, AsyncEnv)
1216 {
1217     testEncryptDecryptBigData({CKMC_ALGO_AES_CTR, 128});
1218 }
1219
1220 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CTR_192, SyncEnv, AsyncEnv)
1221 {
1222     testEncryptDecryptBigData({CKMC_ALGO_AES_CTR, 192});
1223 }
1224
1225 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CTR_256, SyncEnv, AsyncEnv)
1226 {
1227     testEncryptDecryptBigData({CKMC_ALGO_AES_CTR, 256});
1228 }
1229
1230 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CFB_128, SyncEnv, AsyncEnv)
1231 {
1232     testEncryptDecryptBigData({CKMC_ALGO_AES_CFB, 128});
1233 }
1234
1235 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CFB_192, SyncEnv, AsyncEnv)
1236 {
1237     testEncryptDecryptBigData({CKMC_ALGO_AES_CFB, 192});
1238 }
1239
1240 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CFB_256, SyncEnv, AsyncEnv)
1241 {
1242     testEncryptDecryptBigData({CKMC_ALGO_AES_CFB, 256});
1243 }
1244
1245 /////////////////////////////////////////
1246 // Algorithm specific tests
1247 /////////////////////////////////////////
1248
1249 RUNNER_TEST_MULTIPLE(TED_1005_no_iv_enc, SyncEnv, AsyncEnv)
1250 {
1251     testNoIvEnc({CKMC_ALGO_AES_CTR, 128});
1252     testNoIvEnc({CKMC_ALGO_AES_CTR, 192});
1253     testNoIvEnc({CKMC_ALGO_AES_CTR, 256});
1254     testNoIvEnc({CKMC_ALGO_AES_CBC, 128});
1255     testNoIvEnc({CKMC_ALGO_AES_CBC, 192});
1256     testNoIvEnc({CKMC_ALGO_AES_CBC, 256});
1257     testNoIvEnc({CKMC_ALGO_AES_CFB, 128});
1258     testNoIvEnc({CKMC_ALGO_AES_CFB, 192});
1259     testNoIvEnc({CKMC_ALGO_AES_CFB, 256});
1260     testNoIvEnc({CKMC_ALGO_AES_GCM, 128});
1261     testNoIvEnc({CKMC_ALGO_AES_GCM, 192});
1262     testNoIvEnc({CKMC_ALGO_AES_GCM, 256});
1263 }
1264
1265 RUNNER_TEST_MULTIPLE(TED_1010_invalid_iv_enc, SyncEnv, AsyncEnv)
1266 {
1267     testInvalidIvEnc({CKMC_ALGO_AES_CTR, 128});
1268     testInvalidIvEnc({CKMC_ALGO_AES_CTR, 192});
1269     testInvalidIvEnc({CKMC_ALGO_AES_CTR, 256});
1270     testInvalidIvEnc({CKMC_ALGO_AES_CBC, 128});
1271     testInvalidIvEnc({CKMC_ALGO_AES_CBC, 192});
1272     testInvalidIvEnc({CKMC_ALGO_AES_CBC, 256});
1273     testInvalidIvEnc({CKMC_ALGO_AES_CFB, 128});
1274     testInvalidIvEnc({CKMC_ALGO_AES_CFB, 192});
1275     testInvalidIvEnc({CKMC_ALGO_AES_CFB, 256});
1276 }
1277
1278 RUNNER_TEST_MULTIPLE(TED_1015_no_iv_dec, SyncEnv, AsyncEnv)
1279 {
1280     testNoIvDec({CKMC_ALGO_AES_CTR, 128});
1281     testNoIvDec({CKMC_ALGO_AES_CTR, 192});
1282     testNoIvDec({CKMC_ALGO_AES_CTR, 256});
1283     testNoIvDec({CKMC_ALGO_AES_CBC, 128});
1284     testNoIvDec({CKMC_ALGO_AES_CBC, 192});
1285     testNoIvDec({CKMC_ALGO_AES_CBC, 256});
1286     testNoIvDec({CKMC_ALGO_AES_CFB, 128});
1287     testNoIvDec({CKMC_ALGO_AES_CFB, 192});
1288     testNoIvDec({CKMC_ALGO_AES_CFB, 256});
1289     testNoIvDec({CKMC_ALGO_AES_GCM, 128});
1290     testNoIvDec({CKMC_ALGO_AES_GCM, 192});
1291     testNoIvDec({CKMC_ALGO_AES_GCM, 256});
1292 }
1293
1294 RUNNER_TEST_MULTIPLE(TED_1020_invalid_iv_dec, SyncEnv, AsyncEnv)
1295 {
1296     testInvalidIvDec({CKMC_ALGO_AES_CTR, 128});
1297     testInvalidIvDec({CKMC_ALGO_AES_CTR, 192});
1298     testInvalidIvDec({CKMC_ALGO_AES_CTR, 256});
1299     testInvalidIvDec({CKMC_ALGO_AES_CBC, 128});
1300     testInvalidIvDec({CKMC_ALGO_AES_CBC, 192});
1301     testInvalidIvDec({CKMC_ALGO_AES_CBC, 256});
1302     testInvalidIvDec({CKMC_ALGO_AES_CFB, 128});
1303     testInvalidIvDec({CKMC_ALGO_AES_CFB, 192});
1304     testInvalidIvDec({CKMC_ALGO_AES_CFB, 256});
1305 }
1306
1307 RUNNER_TEST_MULTIPLE(TED_1050_data_integrity, SyncEnv, AsyncEnv)
1308 {
1309     testIntegrity({CKMC_ALGO_AES_CTR, 128});
1310     testIntegrity({CKMC_ALGO_AES_CTR, 192});
1311     testIntegrity({CKMC_ALGO_AES_CTR, 256});
1312     testIntegrity({CKMC_ALGO_AES_CBC, 128});
1313     testIntegrity({CKMC_ALGO_AES_CBC, 192});
1314     testIntegrity({CKMC_ALGO_AES_CBC, 256});
1315     testIntegrity({CKMC_ALGO_AES_CFB, 128});
1316     testIntegrity({CKMC_ALGO_AES_CFB, 192});
1317     testIntegrity({CKMC_ALGO_AES_CFB, 256});
1318 }
1319
1320 RUNNER_TEST_MULTIPLE(TED_1100_ctr_encryption_invalid_length, SyncEnv, AsyncEnv)
1321 {
1322     testCtrEncryptionInvalidLength({CKMC_ALGO_AES_CTR, 128});
1323     testCtrEncryptionInvalidLength({CKMC_ALGO_AES_CTR, 192});
1324     testCtrEncryptionInvalidLength({CKMC_ALGO_AES_CTR, 256});
1325 }
1326
1327 RUNNER_TEST_MULTIPLE(TED_1105_ctr_encryption_valid_length, SyncEnv, AsyncEnv)
1328 {
1329     RUNNER_IGNORED_MSG("Openssl supports only 128-bit AES CTR length");
1330     testCtrEncryptionValidLength({CKMC_ALGO_AES_CTR, 128});
1331     testCtrEncryptionValidLength({CKMC_ALGO_AES_CTR, 192});
1332     testCtrEncryptionValidLength({CKMC_ALGO_AES_CTR, 256});
1333 }
1334
1335 RUNNER_TEST_MULTIPLE(TED_1110_ctr_decryption_invalid_length, SyncEnv, AsyncEnv)
1336 {
1337     testCtrDecryptionInvalidLength({CKMC_ALGO_AES_CTR, 128});
1338     testCtrDecryptionInvalidLength({CKMC_ALGO_AES_CTR, 192});
1339     testCtrDecryptionInvalidLength({CKMC_ALGO_AES_CTR, 256});
1340 }
1341
1342 RUNNER_TEST_MULTIPLE(TED_1115_ctr_decryption_valid_length, SyncEnv, AsyncEnv)
1343 {
1344     RUNNER_IGNORED_MSG("Openssl supports only 128-bit AES CTR length");
1345     testCtrDecryptionValidLength({CKMC_ALGO_AES_CTR, 128});
1346     testCtrDecryptionValidLength({CKMC_ALGO_AES_CTR, 192});
1347     testCtrDecryptionValidLength({CKMC_ALGO_AES_CTR, 256});
1348 }
1349
1350 RUNNER_TEST_MULTIPLE(TED_1200_gcm_encryption_tag_len, SyncEnv, AsyncEnv)
1351 {
1352     testGcmEncryptionTagLen({CKMC_ALGO_AES_GCM, 128});
1353     testGcmEncryptionTagLen({CKMC_ALGO_AES_GCM, 192});
1354     testGcmEncryptionTagLen({CKMC_ALGO_AES_GCM, 256});
1355 }
1356
1357 RUNNER_TEST_MULTIPLE(TED_1210_gcm_decryption_tag_len, SyncEnv, AsyncEnv)
1358 {
1359     testGcmDecryptionTagLen({CKMC_ALGO_AES_GCM, 128});
1360     testGcmDecryptionTagLen({CKMC_ALGO_AES_GCM, 192});
1361     testGcmDecryptionTagLen({CKMC_ALGO_AES_GCM, 256});
1362 }
1363
1364 RUNNER_TEST_MULTIPLE(TED_1230_gcm_wrong_tag, SyncEnv, AsyncEnv)
1365 {
1366     testGcmWrongTag({CKMC_ALGO_AES_GCM, 128});
1367     testGcmWrongTag({CKMC_ALGO_AES_GCM, 192});
1368     testGcmWrongTag({CKMC_ALGO_AES_GCM, 256});
1369 }
1370
1371 RUNNER_TEST_MULTIPLE(TED_1240_gcm_different_iv_sizes, SyncEnv, AsyncEnv)
1372 {
1373     testGcmDifferentIvSizes({CKMC_ALGO_AES_GCM, 128});
1374     testGcmDifferentIvSizes({CKMC_ALGO_AES_GCM, 192});
1375     testGcmDifferentIvSizes({CKMC_ALGO_AES_GCM, 256});
1376 }
1377
1378 RUNNER_TEST_MULTIPLE(TED_1250_gcm_aad, SyncEnv, AsyncEnv)
1379 {
1380     encryptionWithCustomData({CKMC_ALGO_AES_GCM, 128}, CKMC_PARAM_ED_AAD);
1381     encryptionWithCustomData({CKMC_ALGO_AES_GCM, 192}, CKMC_PARAM_ED_AAD);
1382     encryptionWithCustomData({CKMC_ALGO_AES_GCM, 256}, CKMC_PARAM_ED_AAD);
1383 }
1384
1385 RUNNER_TEST_MULTIPLE(TED_1300_rsa_label, SyncEnv, AsyncEnv)
1386 {
1387     RUNNER_IGNORED_MSG("RSA-OAEP labels are not supported in openssl");
1388     encryptionWithCustomData({CKMC_ALGO_RSA_OAEP, 1024}, CKMC_PARAM_ED_LABEL);
1389     encryptionWithCustomData({CKMC_ALGO_RSA_OAEP, 2048}, CKMC_PARAM_ED_LABEL);
1390     encryptionWithCustomData({CKMC_ALGO_RSA_OAEP, 4096}, CKMC_PARAM_ED_LABEL);
1391 }
1392
1393 RUNNER_TEST_MULTIPLE(TED_1330_rsa_longest_data, SyncEnv, AsyncEnv)
1394 {
1395     testRsaLongestData({CKMC_ALGO_RSA_OAEP, 1024}, 86);
1396     testRsaLongestData({CKMC_ALGO_RSA_OAEP, 2048}, 214);
1397     testRsaLongestData({CKMC_ALGO_RSA_OAEP, 4096}, 470);
1398 }
1399
1400 RUNNER_TEST_MULTIPLE(TED_1350_rsa_data_too_long, SyncEnv, AsyncEnv)
1401 {
1402     testRsaDataTooLong({CKMC_ALGO_RSA_OAEP, 1024}, 87);
1403     testRsaDataTooLong({CKMC_ALGO_RSA_OAEP, 2048}, 215);
1404     testRsaDataTooLong({CKMC_ALGO_RSA_OAEP, 4096}, 471);
1405 }
1406
1407 /////////////////////////////////////////
1408 // Asynchronous only tests
1409 /////////////////////////////////////////
1410 RUNNER_TEST(TED_2000_enc_no_observer_async, AsyncEnv)
1411 {
1412     testAllAlgorithms([](const Algo& algo){
1413         // prepare buffers
1414         RawBuffer plain = createRandomBuffer(BUF_LEN);
1415
1416         // keys
1417         KeyAliasPair aliases = getKey(algo, PRIMARY);
1418
1419         // params
1420         ckmc_param_list_h handle = NULL;
1421         assert_positive(ckmc_generate_new_params, algo.type, &handle);
1422         ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
1423         setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
1424
1425         // encrypt
1426         test_no_observer(&ManagerAsync::encrypt,
1427                          *reinterpret_cast<CryptoAlgorithm*>(params.get()),
1428                          aliases.pub,
1429                          Password(),
1430                          plain);
1431     });
1432 }
1433
1434 RUNNER_TEST(TED_2010_dec_no_observer_async, AsyncEnv)
1435 {
1436     testAllAlgorithms([](const Algo& algo){
1437         // encrypt
1438         auto ret = encrypt(algo, PLAIN_DATA);
1439         RawBuffer encrypted(ret.encrypted->data, ret.encrypted->data + ret.encrypted->size);
1440
1441         // decrypt
1442         test_no_observer(&ManagerAsync::decrypt,
1443                          *reinterpret_cast<CryptoAlgorithm*>(ret.params.get()),
1444                          ret.prvKey,
1445                          Password(),
1446                          encrypted);
1447     });
1448 }
1449
1450 /////////////////////////////////////////
1451 // Mulithreaded test for synchronous API
1452 /////////////////////////////////////////
1453 RUNNER_TEST(TED_3000_muliple_threads, SyncEnv)
1454 {
1455     std::vector<std::thread> threads;
1456     threads.reserve(10);
1457     for(unsigned i = 0; i < 10;++i)
1458         threads.emplace_back([]{ testEncryptDecryptBigData({CKMC_ALGO_AES_CBC, 256}); });
1459     for (auto& thread : threads)
1460         thread.join();
1461 }