summaryrefslogtreecommitdiff
path: root/src/manager/service/key-provider.cpp
blob: 60cce238efa18d7ce0f26193c8656b34aff6a687 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
#include <exception.h>
#include <key-provider.h>
#include <dpl/log/log.h>

namespace {

template<typename T>
CKM::RawBuffer toRawBuffer(const T &data)
{
	CKM::RawBuffer output;
	const unsigned char *ptr = reinterpret_cast<const unsigned char *>(&data);
	output.assign(ptr, ptr + sizeof(T));
	return output;
}

// You cannot use toRawBuffer template with pointers
template<typename T>
CKM::RawBuffer toRawBuffer(T *)
{
	class NoPointerAllowed {
		NoPointerAllowed() {}
	};
	NoPointerAllowed a;
	return CKM::RawBuffer();
}

} // anonymous namespace

using namespace CKM;

WrappedKeyAndInfoContainer::WrappedKeyAndInfoContainer()
{
	wrappedKeyAndInfo = new WrappedKeyAndInfo;
	memset(wrappedKeyAndInfo, 0, sizeof(WrappedKeyAndInfo));
}

WrappedKeyAndInfoContainer::WrappedKeyAndInfoContainer(const unsigned char
		*data)
{
	wrappedKeyAndInfo = new WrappedKeyAndInfo;
	memcpy(wrappedKeyAndInfo, data, sizeof(WrappedKeyAndInfo));
}

WrappedKeyAndInfo &WrappedKeyAndInfoContainer::getWrappedKeyAndInfo()
{
	return *wrappedKeyAndInfo;
}

void WrappedKeyAndInfoContainer::setKeyInfoKeyLength(const unsigned int length)
{
	wrappedKeyAndInfo->keyInfo.keyLength = length;
}

void WrappedKeyAndInfoContainer::setKeyInfoLabel(const std::string label)
{
	strncpy(
		wrappedKeyAndInfo->keyInfo.label,
		label.c_str(),
		MAX_LABEL_SIZE);
}

void WrappedKeyAndInfoContainer::setKeyInfoSalt(const unsigned char *salt,
		const int size)
{
	memcpy(wrappedKeyAndInfo->keyInfo.salt, salt, size);
}

void WrappedKeyAndInfoContainer::setKeyInfo(const KeyComponentsInfo
		*keyComponentsInfo)
{
	memcpy(&(wrappedKeyAndInfo->keyInfo), keyComponentsInfo,
		   sizeof(KeyComponentsInfo));
}

WrappedKeyAndInfoContainer::~WrappedKeyAndInfoContainer()
{
	delete wrappedKeyAndInfo;
}

KeyAndInfoContainer::KeyAndInfoContainer()
{
	keyAndInfo = new KeyAndInfo;
	memset(keyAndInfo, 0, sizeof(KeyAndInfo));
}

KeyAndInfoContainer::KeyAndInfoContainer(const unsigned char *data)
{
	keyAndInfo = new KeyAndInfo;
	memcpy(keyAndInfo, data, sizeof(KeyAndInfo));
}

KeyAndInfo &KeyAndInfoContainer::getKeyAndInfo()
{
	return *keyAndInfo;
}

void KeyAndInfoContainer::setKeyInfoKeyLength(unsigned int length)
{
	keyAndInfo->keyInfo.keyLength = length;
}

void KeyAndInfoContainer::setKeyInfo(const KeyComponentsInfo *keyComponentsInfo)
{
	memcpy(&(keyAndInfo->keyInfo), keyComponentsInfo, sizeof(KeyComponentsInfo));
}

KeyAndInfoContainer::~KeyAndInfoContainer()
{
	// overwrite key
	char *ptr = reinterpret_cast<char *>(keyAndInfo);
	memset(ptr, 0, sizeof(KeyAndInfo));

	// verification
	for (size_t size = 0; size < sizeof(KeyAndInfo); ++size) {
		if (ptr[size])
			LogError("Write momory error! Memory used by key was not owerwritten.");
	}

	delete keyAndInfo;
}

KeyProvider::KeyProvider() :
	m_kmcDKEK(NULL),
	m_isInitialized(false)
{
	LogDebug("Created empty KeyProvider");
}

KeyProvider::KeyProvider(
	const RawBuffer &domainKEKInWrapForm,
	const Password &password) :
	m_kmcDKEK(new KeyAndInfoContainer()),
	m_isInitialized(true)
{
	if (!m_isInitialized)
		ThrowErr(Exc::InternalError, "Object not initialized!. Should not happened");

	if (domainKEKInWrapForm.size() != sizeof(WrappedKeyAndInfo)) {
		LogError("input size:" << domainKEKInWrapForm.size()
				 << " Expected: " << sizeof(WrappedKeyAndInfo));
		ThrowErr(Exc::InternalError,
				 "buffer doesn't have proper size to store WrappedKeyAndInfo in KeyProvider Constructor");
	}

	WrappedKeyAndInfoContainer wkmcDKEK = WrappedKeyAndInfoContainer(
			domainKEKInWrapForm.data());

	char *concat_user_pass = NULL;
	uint8_t PKEK1[MAX_KEY_SIZE];

	concat_user_pass = concat_password_user(
						   wkmcDKEK.getWrappedKeyAndInfo().keyInfo.label,
						   password.c_str());

	if (!PKCS5_PBKDF2_HMAC_SHA1(
				concat_user_pass,
				strlen(concat_user_pass),
				wkmcDKEK.getWrappedKeyAndInfo().keyInfo.salt,
				MAX_SALT_SIZE,
				PBKDF2_ITERATIONS,
				MAX_KEY_SIZE,
				PKEK1)) {
		delete[] concat_user_pass;
		ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
	}

	delete[] concat_user_pass;

	int keyLength;

	if (0 > (keyLength = decryptAes256Gcm(
							 wkmcDKEK.getWrappedKeyAndInfo().wrappedKey,
							 wkmcDKEK.getWrappedKeyAndInfo().keyInfo.keyLength,
							 wkmcDKEK.getWrappedKeyAndInfo().keyInfo.tag,
							 PKEK1,
							 wkmcDKEK.getWrappedKeyAndInfo().keyInfo.iv,
							 m_kmcDKEK->getKeyAndInfo().key))) {
		ThrowErr(Exc::AuthenticationFailed,
				 "VerifyDomainKEK failed in KeyProvider Constructor");
	}

	m_kmcDKEK->setKeyInfo(&(wkmcDKEK.getWrappedKeyAndInfo().keyInfo));
	m_kmcDKEK->setKeyInfoKeyLength((unsigned int)keyLength);
}

KeyProvider &KeyProvider::operator=(KeyProvider &&second)
{
	LogDebug("Moving KeyProvider");

	if (this == &second)
		return *this;

	m_isInitialized = second.m_isInitialized;
	m_kmcDKEK = second.m_kmcDKEK;
	second.m_isInitialized = false;
	second.m_kmcDKEK = NULL;
	return *this;
}

KeyProvider::KeyProvider(KeyProvider &&second)
{
	LogDebug("Moving KeyProvider");
	m_isInitialized = second.m_isInitialized;
	m_kmcDKEK = second.m_kmcDKEK;
	second.m_isInitialized = false;
	second.m_kmcDKEK = NULL;
}

bool KeyProvider::isInitialized()
{
	return m_isInitialized;
}

RawBuffer KeyProvider::getPureDomainKEK()
{
	if (!m_isInitialized)
		ThrowErr(Exc::InternalError, "Object not initialized!");

	// TODO secure
	return RawBuffer(m_kmcDKEK->getKeyAndInfo().key,
					 (m_kmcDKEK->getKeyAndInfo().key) +
					 m_kmcDKEK->getKeyAndInfo().keyInfo.keyLength);
}

RawBuffer KeyProvider::getWrappedDomainKEK(const Password &password)
{
	if (!m_isInitialized)
		ThrowErr(Exc::InternalError, "Object not initialized!");

	WrappedKeyAndInfoContainer wkmcDKEK = WrappedKeyAndInfoContainer();

	char *concat_user_pass = NULL;
	uint8_t PKEK1[MAX_KEY_SIZE];

	concat_user_pass = concat_password_user(
						   m_kmcDKEK->getKeyAndInfo().keyInfo.label,
						   password.c_str());

	if (!PKCS5_PBKDF2_HMAC_SHA1(
				concat_user_pass,
				strlen(concat_user_pass),
				m_kmcDKEK->getKeyAndInfo().keyInfo.salt,
				MAX_SALT_SIZE,
				PBKDF2_ITERATIONS,
				MAX_KEY_SIZE,
				PKEK1)) {
		delete[] concat_user_pass;
		ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
	}

	delete[] concat_user_pass;

	wkmcDKEK.setKeyInfo(&(m_kmcDKEK->getKeyAndInfo().keyInfo));

	int wrappedKeyLength;

	if (0 > (wrappedKeyLength = encryptAes256Gcm(
									m_kmcDKEK->getKeyAndInfo().key,
									m_kmcDKEK->getKeyAndInfo().keyInfo.keyLength,
									PKEK1,
									m_kmcDKEK->getKeyAndInfo().keyInfo.iv,
									wkmcDKEK.getWrappedKeyAndInfo().wrappedKey,
									wkmcDKEK.getWrappedKeyAndInfo().keyInfo.tag)))
		ThrowErr(Exc::InternalError, "WrapDKEK Failed in KeyProvider::getDomainKEK");

	wkmcDKEK.setKeyInfoKeyLength((unsigned int)wrappedKeyLength);

	LogDebug("getDomainKEK(password) Success");
	return toRawBuffer(wkmcDKEK.getWrappedKeyAndInfo());
}


RawBuffer KeyProvider::getPureDEK(const RawBuffer &DEKInWrapForm)
{
	if (!m_isInitialized)
		ThrowErr(Exc::InternalError, "Object not initialized!");

	if (DEKInWrapForm.size() != sizeof(WrappedKeyAndInfo)) {
		LogError("input size:" << DEKInWrapForm.size()
				 << " Expected: " << sizeof(WrappedKeyAndInfo));
		ThrowErr(Exc::InternalError,
				 "buffer doesn't have proper size to store "
				 "WrappedKeyAndInfo in KeyProvider::getPureDEK");
	}

	KeyAndInfoContainer kmcDEK = KeyAndInfoContainer();
	WrappedKeyAndInfoContainer wkmcDEK = WrappedKeyAndInfoContainer(
			DEKInWrapForm.data());

	uint8_t PKEK2[MAX_KEY_SIZE];
	int keyLength;

	if (!PKCS5_PBKDF2_HMAC_SHA1(
				wkmcDEK.getWrappedKeyAndInfo().keyInfo.label,
				strlen(wkmcDEK.getWrappedKeyAndInfo().keyInfo.label),
				m_kmcDKEK->getKeyAndInfo().key,
				MAX_SALT_SIZE,
				PBKDF2_ITERATIONS,
				MAX_KEY_SIZE,
				PKEK2))
		ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");

	if (0 > (keyLength = decryptAes256Gcm(
							 wkmcDEK.getWrappedKeyAndInfo().wrappedKey,
							 wkmcDEK.getWrappedKeyAndInfo().keyInfo.keyLength,
							 wkmcDEK.getWrappedKeyAndInfo().keyInfo.tag,
							 PKEK2,
							 wkmcDEK.getWrappedKeyAndInfo().keyInfo.iv,
							 kmcDEK.getKeyAndInfo().key)))
		ThrowErr(Exc::InternalError,
				 "UnwrapDEK Failed in KeyProvider::getPureDEK");

	kmcDEK.setKeyInfoKeyLength((unsigned int)keyLength);

	LogDebug("getPureDEK SUCCESS");
	return RawBuffer(
			   kmcDEK.getKeyAndInfo().key,
			   (kmcDEK.getKeyAndInfo().key) + kmcDEK.getKeyAndInfo().keyInfo.keyLength);
}

RawBuffer KeyProvider::generateDEK(const std::string &smackLabel)
{
	if (!m_isInitialized)
		ThrowErr(Exc::InternalError, "Object not initialized!");

	WrappedKeyAndInfoContainer wkmcDEK = WrappedKeyAndInfoContainer();
	std::string resized_smackLabel;

	if (smackLabel.length() < APP_LABEL_SIZE)
		resized_smackLabel = smackLabel;
	else
		resized_smackLabel = smackLabel.substr(0, APP_LABEL_SIZE - 1);

	uint8_t key[MAX_KEY_SIZE], PKEK2[MAX_KEY_SIZE];

	if (!RAND_bytes(key, m_kmcDKEK->getKeyAndInfo().keyInfo.keyLength) ||
			!RAND_bytes(wkmcDEK.getWrappedKeyAndInfo().keyInfo.iv, MAX_IV_SIZE))
		ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");

	if (!PKCS5_PBKDF2_HMAC_SHA1(
				resized_smackLabel.c_str(),
				strlen(resized_smackLabel.c_str()),
				m_kmcDKEK->getKeyAndInfo().key,
				MAX_SALT_SIZE,
				PBKDF2_ITERATIONS,
				MAX_KEY_SIZE,
				PKEK2))
		ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");

	int wrappedKeyLength;

	if (0 > (wrappedKeyLength = encryptAes256Gcm(
									key,
									m_kmcDKEK->getKeyAndInfo().keyInfo.keyLength,
									PKEK2,
									wkmcDEK.getWrappedKeyAndInfo().keyInfo.iv,
									wkmcDEK.getWrappedKeyAndInfo().wrappedKey,
									wkmcDEK.getWrappedKeyAndInfo().keyInfo.tag)))
		ThrowErr(Exc::InternalError, "GenerateDEK Failed in KeyProvider::generateDEK");

	wkmcDEK.setKeyInfoKeyLength((unsigned int)wrappedKeyLength);
	wkmcDEK.setKeyInfoLabel(resized_smackLabel);

	LogDebug("GenerateDEK Success");
	return toRawBuffer(wkmcDEK.getWrappedKeyAndInfo());
}

RawBuffer KeyProvider::reencrypt(
	const RawBuffer &domainKEKInWrapForm,
	const Password &oldPass,
	const Password &newPass)
{
	if (domainKEKInWrapForm.size() != sizeof(WrappedKeyAndInfo)) {
		LogError("input size:" << domainKEKInWrapForm.size()
				 << " Expected: " << sizeof(WrappedKeyAndInfo));
		ThrowErr(Exc::InternalError,
				 "buffer doesn't have proper size to store "
				 "WrappedKeyAndInfo in KeyProvider::reencrypt");
	}

	WrappedKeyAndInfoContainer wkmcOldDKEK = WrappedKeyAndInfoContainer(
				domainKEKInWrapForm.data());
	WrappedKeyAndInfoContainer wkmcNewDKEK = WrappedKeyAndInfoContainer();
	KeyAndInfoContainer kmcDKEK = KeyAndInfoContainer();

	char *concat_user_pass = NULL;
	uint8_t PKEK1[MAX_KEY_SIZE];
	int keyLength = 0;


	concat_user_pass = concat_password_user(
						   wkmcOldDKEK.getWrappedKeyAndInfo().keyInfo.label,
						   oldPass.c_str());

	if (!PKCS5_PBKDF2_HMAC_SHA1(
				concat_user_pass,
				strlen(concat_user_pass),
				wkmcOldDKEK.getWrappedKeyAndInfo().keyInfo.salt,
				MAX_SALT_SIZE,
				PBKDF2_ITERATIONS,
				MAX_KEY_SIZE,
				PKEK1)) {
		delete[] concat_user_pass;
		ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
	}

	delete[] concat_user_pass;

	if (0 > (keyLength = decryptAes256Gcm(
							 wkmcOldDKEK.getWrappedKeyAndInfo().wrappedKey,
							 wkmcOldDKEK.getWrappedKeyAndInfo().keyInfo.keyLength,
							 wkmcOldDKEK.getWrappedKeyAndInfo().keyInfo.tag,
							 PKEK1,
							 wkmcOldDKEK.getWrappedKeyAndInfo().keyInfo.iv,
							 kmcDKEK.getKeyAndInfo().key)))
		ThrowErr(Exc::AuthenticationFailed, "Incorrect Old Password ");

	kmcDKEK.setKeyInfo(&(wkmcOldDKEK.getWrappedKeyAndInfo().keyInfo));
	kmcDKEK.setKeyInfoKeyLength((unsigned int)keyLength);

	concat_user_pass = concat_password_user(
						   kmcDKEK.getKeyAndInfo().keyInfo.label,
						   newPass.c_str());

	if (!PKCS5_PBKDF2_HMAC_SHA1(
				concat_user_pass,
				strlen(concat_user_pass),
				kmcDKEK.getKeyAndInfo().keyInfo.salt,
				MAX_SALT_SIZE,
				PBKDF2_ITERATIONS,
				MAX_KEY_SIZE,
				PKEK1)) {
		delete[] concat_user_pass;
		ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
	}

	delete[] concat_user_pass;

	int wrappedKeyLength = 0;
	wkmcNewDKEK.setKeyInfo(&(kmcDKEK.getKeyAndInfo().keyInfo));

	if (0 > (wrappedKeyLength = encryptAes256Gcm(
									kmcDKEK.getKeyAndInfo().key,
									kmcDKEK.getKeyAndInfo().keyInfo.keyLength,
									PKEK1,
									kmcDKEK.getKeyAndInfo().keyInfo.iv,
									wkmcNewDKEK.getWrappedKeyAndInfo().wrappedKey,
									wkmcNewDKEK.getWrappedKeyAndInfo().keyInfo.tag)))
		ThrowErr(Exc::InternalError,
				 "UpdateDomainKEK in KeyProvider::reencrypt Failed");

	wkmcNewDKEK.setKeyInfoKeyLength((unsigned int)wrappedKeyLength);

	LogDebug("reencrypt SUCCESS");
	return toRawBuffer(wkmcNewDKEK.getWrappedKeyAndInfo());
}


RawBuffer KeyProvider::generateDomainKEK(
	const std::string &user,
	const Password &userPassword)
{
	WrappedKeyAndInfoContainer wkmcDKEK = WrappedKeyAndInfoContainer();
	uint8_t key[MAX_KEY_SIZE], PKEK1[MAX_KEY_SIZE];

	if (!RAND_bytes(wkmcDKEK.getWrappedKeyAndInfo().keyInfo.salt, MAX_SALT_SIZE) ||
			!RAND_bytes(key, MAX_KEY_SIZE) ||
			!RAND_bytes(wkmcDKEK.getWrappedKeyAndInfo().keyInfo.iv, MAX_IV_SIZE))
		ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");

	int wrappedKeyLength;
	char *concat_user_pass = NULL;
	concat_user_pass = concat_password_user(user.c_str(), userPassword.c_str());

	if (!PKCS5_PBKDF2_HMAC_SHA1(
				concat_user_pass,
				strlen(concat_user_pass),
				wkmcDKEK.getWrappedKeyAndInfo().keyInfo.salt,
				MAX_SALT_SIZE,
				PBKDF2_ITERATIONS,
				MAX_KEY_SIZE,
				PKEK1)) {
		delete[] concat_user_pass;
		ThrowErr(Exc::InternalError, "OPENSSL_ENGINED_ERROR");
	}

	delete[] concat_user_pass;

	if (0 > (wrappedKeyLength = encryptAes256Gcm(
									key,
									MAX_KEY_SIZE,
									PKEK1,
									wkmcDKEK.getWrappedKeyAndInfo().keyInfo.iv,
									wkmcDKEK.getWrappedKeyAndInfo().wrappedKey,
									wkmcDKEK.getWrappedKeyAndInfo().keyInfo.tag)))
		ThrowErr(Exc::InternalError,
				 "GenerateDomainKEK Failed in KeyProvider::generateDomainKEK");

	wkmcDKEK.setKeyInfoKeyLength((unsigned int)wrappedKeyLength);
	wkmcDKEK.setKeyInfoLabel(user);

	LogDebug("generateDomainKEK Success");
	return toRawBuffer(wkmcDKEK.getWrappedKeyAndInfo());
}

int KeyProvider::initializeLibrary()
{
	LogDebug("initializeLibrary Success");
	return SUCCESS;
}

int KeyProvider::closeLibrary()
{
	LogDebug("closeLibrary Success");
	return SUCCESS;
}

KeyProvider::~KeyProvider()
{
	LogDebug("KeyProvider Destructor");
}

int KeyProvider::encryptAes256Gcm(const unsigned char *plaintext,
								  int plaintext_len, const unsigned char *key, const unsigned char *iv,
								  unsigned char *ciphertext, unsigned char *tag)
{
	EVP_CIPHER_CTX *ctx;
	int len;
	int ciphertext_len = 0;

	if (!(ctx = EVP_CIPHER_CTX_new()))
		return OPENSSL_ENGINE_ERROR;

	if (!EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
		return OPENSSL_ENGINE_ERROR;

	if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv))
		return OPENSSL_ENGINE_ERROR;

	if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, MAX_IV_SIZE, NULL))
		return OPENSSL_ENGINE_ERROR;

	if (!EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
		return OPENSSL_ENGINE_ERROR;

	ciphertext_len = len;

	if (!EVP_EncryptFinal_ex(ctx, ciphertext + len, &len))
		return OPENSSL_ENGINE_ERROR;

	ciphertext_len += len;

	if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, MAX_IV_SIZE, tag))
		return OPENSSL_ENGINE_ERROR;

	EVP_CIPHER_CTX_free(ctx);

	return ciphertext_len;
}

int KeyProvider::decryptAes256Gcm(const unsigned char *ciphertext,
								  int ciphertext_len, unsigned char *tag, const unsigned char *key,
								  const unsigned char *iv, unsigned char *plaintext)
{
	EVP_CIPHER_CTX *ctx;
	int len;
	int plaintext_len;
	int ret;

	if (!(ctx = EVP_CIPHER_CTX_new()))
		return OPENSSL_ENGINE_ERROR;

	if (!EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
		return OPENSSL_ENGINE_ERROR;

	if (!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv))
		return OPENSSL_ENGINE_ERROR;

	if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, MAX_IV_SIZE, NULL))
		return OPENSSL_ENGINE_ERROR;

	if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, MAX_IV_SIZE, tag))
		return OPENSSL_ENGINE_ERROR;

	if (!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
		return OPENSSL_ENGINE_ERROR;

	plaintext_len = len;

	if (!(ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len)))
		return OPENSSL_ENGINE_ERROR;

	EVP_CIPHER_CTX_free(ctx);

	if (ret > 0) {
		plaintext_len += len;
		return plaintext_len;
	} else {
		return -1;
	}
}

char *KeyProvider::concat_password_user(const char *user, const char *password)
{
	std::string result(password);
	result += user;

	if (strlen(user) > MAX_LABEL_SIZE - 1)
		result.resize(strlen(password) + MAX_LABEL_SIZE - 1);

	char *ret = new char[result.size() + 1];
	memcpy(ret, result.c_str(), result.size() + 1);
	return ret;
}