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