-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessage.cpp
More file actions
871 lines (775 loc) · 26.4 KB
/
message.cpp
File metadata and controls
871 lines (775 loc) · 26.4 KB
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
#include <iostream>
#include <ctime>
#include <chrono>
#include <stdexcept>
#include <string>
#include <variant>
#include <cryptopp/cryptlib.h>
#include <cryptopp/filters.h>
#include <cryptopp/aes.h>
#include <cryptopp/eccrypto.h>
#include <cryptopp/osrng.h>
#include <cryptopp/oids.h>
#include <cryptopp/integer.h>
#include <cryptopp/hkdf.h>
#include <cryptopp/modes.h>
#include <cryptopp/rijndael.h>
#include <cryptopp/gcm.h>
#include <cryptopp/chacha.h>
#include "message.h"
#include "errors.h"
#include <boost/asio/buffer.hpp>
#include <json/json.h>
// key_path: path to keys file
// ct_ip: ciphertext of ip
// ct_ip_len: length of ct_ip
// iv: 16-byte iv
std::string Cryptography::decrypt_ip_with_pepper(std::string key_path, uint8_t *ct_ip, uint16_t ct_ip_len, uint8_t *iv)
{
std::string ip;
LocalKeys local_key(key_path); // get local key parameters like key and length
CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption decipherf;
decipherf.SetKeyWithIV(local_key.keys, local_key.key_len, iv, CryptoPP::AES::BLOCKSIZE);
CryptoPP::StreamTransformationFilter filter(decipherf, new CryptoPP::StringSink(ip), CryptoPP::StreamTransformationFilter::NO_PADDING);
filter.Put(ct_ip, ct_ip_len);
filter.MessageEnd();
// remove padding and pepper
// ip[0] is pad size
ip = ip.erase(0, ip[0]+local_key.pepper_len);
return ip;
}
// key_path: path to keys file
// ip: ip address to encrypt
// out_len: the new output length. Output is returned
// iv: 16-byte IV
uint8_t *Cryptography::encrypt_ip_with_pepper(std::string key_path, std::string ip, uint16_t &out_len, uint8_t *iv)
{
LocalKeys local_key(key_path); // get local key parameters like key and length
uint16_t ip_len = ip.length();
uint16_t new_len = local_key.pepper_len+ip_len;
// pad ip + pepper
uint8_t pad_size;
uint8_t mod = new_len % 16;
pad_size = 16 - mod;
if(mod == 0) // if 32-byte unpadded, then pad_size=0, if zero, than dat[length-1] = pad_size would modify the plaintext
pad_size += 16;
new_len += pad_size;
uint8_t *in = new uint8_t[new_len];
memset(in, 0, pad_size); // pad
memcpy(&in[pad_size], local_key.get_pepper(), local_key.pepper_len); // add pepper
memcpy(&in[pad_size+local_key.pepper_len], ip.c_str(), ip_len); // add ip
in[0] = pad_size; // first byte of data is length
out_len = new_len; // ct len is pt len
// generate IV
CryptoPP::AutoSeededRandomPool rng;
rng.GenerateBlock(iv, CryptoPP::AES::BLOCKSIZE); // 16-byte IV
// encrypt using AES-256-CBC
uint8_t *out = new uint8_t[out_len];
CryptoPP::CBC_Mode<CryptoPP::AES>::Encryption cipherf;
cipherf.SetKeyWithIV(local_key.keys, local_key.key_len, iv, CryptoPP::AES::BLOCKSIZE);
cipherf.ProcessData(out, in, new_len);
delete[] in;
return out;
}
Cryptography::ProtocolData::ProtocolData(uint8_t protocol_no)
{
init(protocol_no);
}
void Cryptography::ProtocolData::init(uint8_t protocol_no)
{
// seperate protocol and curve
protocol = (CommunicationProtocol)(protocol_no % LAST);
uint16_t tmp = protocol_no - protocol_no % LAST;
if(tmp != 0) {
tmp /= LAST;
}
curve = (Curves)(tmp);
// initialize verification algorithm data
if(communication_protocols[protocol].find("ECDSA") != std::string::npos) {
verifier = ECDSA;
} else if(communication_protocols[protocol].find("HMAC") != std::string::npos) {
verifier = HMAC;
} else if (communication_protocols[protocol].find("GCM") != std::string::npos) {
verifier = GCM_VERIFICATION;
} else {
#if DEBUG_MODE
throw std::runtime_error("ProtocolData::init: VERIFICATION_ALGORITHM_NOT_FOUND error. The protocol number is not valid");
#endif
error = VERIFICATION_ALGORITHM_NOT_FOUND;
}
// initialize cipher and decipher object
init_cipher_data();
// if (error == ENCRYPTION_ALGORITHM_NOT_FOUND) {
// error_handle(ENCRYPTION_ALGORITHM_NOT_FOUND, error_handler_encryption_function_not_found, encryption_unexpected_error, get_time);
// }
curve_oid = get_curve();
init_hash_data();
// if (error == HASHING_ALGORITHM_NOT_FOUND) {
// error_handle(HASHING_ALGORITHM_NOT_FOUND, error_handler_hash_function_not_found, hashing_unexpected_error, get_time);
// }
}
Cryptography::ProtocolData::ProtocolData(CommunicationProtocol protocol, Curves curve)
{
this->protocol = protocol;
this->curve = curve;
init_cipher_data();
// if (error == ENCRYPTION_ALGORITHM_NOT_FOUND) {
// error_handle(ENCRYPTION_ALGORITHM_NOT_FOUND, error_handler_encryption_function_not_found, encryption_unexpected_error, get_time);
// }
init_hash_data();
// if (error == HASHING_ALGORITHM_NOT_FOUND) {
// error_handle(HASHING_ALGORITHM_NOT_FOUND, error_handler_hash_function_not_found, hashing_unexpected_error, get_time);
// }
}
uint8_t *Cryptography::ProtocolData::generate_iv()
{
uint8_t *tmp = new uint8_t[iv_size];
CryptoPP::AutoSeededRandomPool rnd;
rnd.GenerateBlock(tmp, iv_size);
return tmp;
}
void Cryptography::ProtocolData::init_cipher_data()
{
if(communication_protocols[protocol].find("AES256") != std::string::npos) {
iv_size = 16;
cipher = AES256;
key_size = 32;
ct_size=16;
block_size = 16;
} else if (communication_protocols[protocol].find("AES192") != std::string::npos) {
iv_size = 16;
cipher = AES192;
key_size = 24;
ct_size=16;
block_size = 16;
} else if (communication_protocols[protocol].find("AES128") != std::string::npos) {
iv_size = 16;
cipher = AES128;
key_size = 16;
ct_size=16;
block_size = 16;
} else if (communication_protocols[protocol].find("CHACHA20") != std::string::npos) {
iv_size = 8;
cipher = CHACHA20;
key_size = 32;
ct_size=64;
block_size = 64;
} else {
error = ENCRYPTION_ALGORITHM_NOT_FOUND;
}
// set cipher mode
if(communication_protocols[protocol].find("CBC") != std::string::npos) {
cipher_mode = CBC;
block_size= ct_size;
} else if(communication_protocols[protocol].find("GCM") != std::string::npos) {
cipher_mode = GCM;
block_size= ct_size; // block-size is ciphertext size in gcm-mode
} else { // e.g. CHACHA20, no cipher mode
cipher_mode = NO_MODE;
}
}
// get information about the hashing algorithm used
// returns hashing algorithm if applicable
void Cryptography::ProtocolData::init_hash_data()
{
if(communication_protocols[protocol].find("SHA256") != std::string::npos) {
hash = SHA256;
hashf = CryptoPP::SHA256();
if(verifier == HMAC) {
mac_size = 32;
} else if(verifier == ECDSA) {
mac_size = get_curve_size(curve)<<1;
} else {
mac_size = 16;
}
} else if(communication_protocols[protocol].find("SHA512") != std::string::npos) {
hash = SHA512;
hashf = CryptoPP::SHA512();
if(verifier == HMAC) {
mac_size = 64;
} else if(verifier == ECDSA) {
mac_size = get_curve_size(curve)<<1;
} else {
mac_size = 16;
}
} else {
error = HASHING_ALGORITHM_NOT_FOUND;
mac_size = default_mac_size;
}
}
// to get cipher: auto cipher = get_cipher();
std::variant<CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption, // aes cbc mode
CryptoPP::GCM<CryptoPP::AES>::Decryption, // aes gcm mode
CryptoPP::ChaCha::Encryption> // ChaCha20
Cryptography::ProtocolData::get_decipher()
{
switch(cipher) {
case AES256:
case AES192:
case AES128:
if(cipher_mode == CBC) {
return CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption();
} else if(cipher_mode == GCM) {
return CryptoPP::GCM<CryptoPP::AES>::Decryption();
}
#if DEBUG_MODE
throw std::runtime_error("ProtocolData::get_decipher: ENCRYPTION_ALGORITHM_NOT_FOUND error. AES algorithm selected but no mode");
#endif
error = ENCRYPTION_ALGORITHM_NOT_FOUND;
return default_decipher();
case CHACHA20:
return CryptoPP::ChaCha::Encryption();
default:
#if DEBUG_MODE
throw std::runtime_error("ProtocolData::get_decipher: ENCRYPTION_ALGORITHM_NOT_FOUND error. The protocol number is not valid");
#endif
error = ENCRYPTION_ALGORITHM_NOT_FOUND;
// default value
return default_decipher();
}
}
// to get cipher: auto cipher = get_cipher();
std::variant<CryptoPP::CBC_Mode<CryptoPP::AES>::Encryption, // aes cbc mode
CryptoPP::GCM<CryptoPP::AES>::Encryption, // aes gcm mode
CryptoPP::ChaCha::Encryption> // ChaCha20
Cryptography::ProtocolData::get_cipher()
{
switch(cipher) {
case AES256:
case AES192:
case AES128:
if(cipher_mode == CBC) {
return CryptoPP::CBC_Mode<CryptoPP::AES>::Encryption();
} else if(cipher_mode == GCM)
return CryptoPP::GCM<CryptoPP::AES>::Encryption();
// default mode
#if DEBUG_MODE
throw std::runtime_error("ProtocolData::get_cipher: ENCRYPTION_ALGORITHM_NOT_FOUND error. AES algorithm selected but no mode");
#endif
error = ENCRYPTION_ALGORITHM_NOT_FOUND;
return default_cipher();
case CHACHA20:
return CryptoPP::ChaCha::Encryption();
default:
#if DEBUG_MODE
throw std::runtime_error("ProtocolData::get_cipher: ENCRYPTION_ALGORITHM_NOT_FOUND error. The protocol number is not valid");
#endif
error = ENCRYPTION_ALGORITHM_NOT_FOUND;
// default value
return default_cipher();
}
}
// to get hash: auto hashf = get_hash();
std::variant<CryptoPP::SHA256, CryptoPP::SHA512> Cryptography::ProtocolData::get_hash()
{
switch(hash) {
case SHA256:
return CryptoPP::SHA256();
case SHA512:
return CryptoPP::SHA512();
default:
#if DEBUG_MODE
throw std::runtime_error("ProtocolData::get_hash: HASHING_ALGORITHM_NOT_FOUND error. The protocol number is not valid");
#endif
error = HASHING_ALGORITHM_NOT_FOUND;
return default_hash();
}
}
// to get hash: auto hashf = get_curve();
// returns curve OID (Object ID)
CryptoPP::OID Cryptography::ProtocolData::get_curve()
{
switch(curve) {
case SECP256K1:
return CryptoPP::ASN1::secp256k1();
case SECP256R1:
return CryptoPP::ASN1::secp256r1();
case SECP521R1:
return CryptoPP::ASN1::secp521r1();
case BRAINPOOL256R1:
return CryptoPP::ASN1::brainpoolP256r1();
case BRAINPOOL512R1:
return CryptoPP::ASN1::brainpoolP512r1();
default:
return default_elliptic_curve;
}
}
Cryptography::Key::Key(ProtocolData &protocol)
{
init(protocol);
}
void Cryptography::Key::init(ProtocolData &protocol)
{
this->protocol = &protocol;
if(key == nullptr)
key = new uint8_t[protocol.key_size];
switch(protocol.curve) {
case SECP256K1:
group.Initialize(CryptoPP::ASN1::secp256k1());
break;
case SECP256R1:
group.Initialize(CryptoPP::ASN1::secp256r1());
break;
case SECP521R1:
group.Initialize(CryptoPP::ASN1::secp521r1());
break;
case BRAINPOOL256R1:
group.Initialize(CryptoPP::ASN1::brainpoolP256r1());
break;
case BRAINPOOL512R1:
group.Initialize(CryptoPP::ASN1::brainpoolP512r1());
break;
default:
#if DEBUG_MODE
throw std::runtime_error("ProtocolData::get_hash: ELLIPTIC_CURVE_NOT_FOUND error. The protocol number is not valid");
#endif
error = ELLIPTIC_CURVE_NOT_FOUND;
// error handling
// error_handle(ELLIPTIC_CURVE_NOT_FOUND,
// [protocol]() mutable { // elliptic curve not found
// if (!USE_DEFAULT_VALUES) // defined in errors.h
// throw ELLIPTIC_CURVE_NOT_FOUND;
// else
// protocol.init(default_communication_protocol+0);
// },
// ErrorHandling::curve_unexpected_error, get_time);
// default value
group.Initialize(default_elliptic_curve);
}
CryptoPP::AutoSeededRandomPool rand;
private_key = CryptoPP::Integer(rand, CryptoPP::Integer::One(), group.GetMaxExponent()); // generate private key
public_key = group.ExponentiateBase(private_key);
}
Cryptography::Key::~Key()
{
if(key != nullptr) {
delete[] key;
}
}
// convert public key to uint8_t*
void Cryptography::Key::integer_to_bytes(CryptoPP::Integer num, uint8_t *&bytes, uint16_t &bytes_len)
{
bytes_len = num.MinEncodedSize(CryptoPP::Integer::UNSIGNED);
bytes = new uint8_t[bytes_len];
num.Encode((uint8_t*)&bytes[0], bytes_len, CryptoPP::Integer::UNSIGNED);
}
CryptoPP::Integer Cryptography::Key::bytes_to_integer(uint8_t *bytes, uint16_t &bytes_len)
{
CryptoPP::Integer x;
x.Decode(bytes, bytes_len);
return x;
}
CryptoPP::ECPPoint Cryptography::Key::reconstruct_point_from_bytes(uint8_t *public_key_x,
uint16_t public_key_x_len,
uint8_t *public_key_y,
uint16_t public_key_y_len)
{
return CryptoPP::ECPPoint(Key::bytes_to_integer(public_key_x, public_key_x_len),
Key::bytes_to_integer(public_key_y, public_key_y_len));
}
// bob's public key is multiplied with alice's to generate the ECDH key.
CryptoPP::DL_GroupParameters_EC<CryptoPP::ECP>::Element
Cryptography::Key::multiply(CryptoPP::DL_GroupParameters_EC<CryptoPP::ECP>::Element b_public_k)
{
return group.GetCurve().ScalarMultiply(b_public_k, private_key);
}
// bob's public key is multiplied with alice's to generate the ECDH key.
CryptoPP::DL_GroupParameters_EC<CryptoPP::ECP>::Element
Cryptography::Key::multiply(CryptoPP::Integer priv_key,
CryptoPP::DL_GroupParameters_EC<CryptoPP::ECP>::Element b_public_k)
{
return group.GetCurve().ScalarMultiply(b_public_k, priv_key);
}
// Hash based key deravation function
// password: ECDH Shared Secret
// password_len: length of password
// salt: optional salt
// salt_len: length of salt
// info: optional info
// info_len: length of info
void Cryptography::Key::hkdf(uint8_t *password, uint16_t password_len, uint8_t *salt, uint16_t salt_len, uint8_t *info, uint16_t info_len)
{
if(protocol->hash == SHA256) {
CryptoPP::HKDF<CryptoPP::SHA256> hkdf;
hkdf.DeriveKey(key, protocol->key_size, password, password_len, salt, salt_len, info, info_len);
} else if (protocol->hash == SHA512) {
CryptoPP::HKDF<CryptoPP::SHA512> hkdf;
hkdf.DeriveKey(key, protocol->key_size, password, password_len, salt, salt_len, info, info_len);
} else {
#if DEBUG_MODE
throw std::runtime_error("Key::hkdf: HASHING_ALGORITHM_NOT_FOUND error. The protocol number is not valid");
#endif
error = HASHING_ALGORITHM_NOT_FOUND;
// default value
CryptoPP::HKDF<default_hash> hkdf;
hkdf.DeriveKey(key, protocol->key_size, (const uint8_t*)"", 0, salt, salt_len, NULL, 0);
}
}
Cryptography::Cipher::Cipher(ProtocolData &protocol, uint8_t *key) : protocol(protocol)
{
this->key = key; // no need to destroy key since it's not allocated here.
switch(protocol.cipher) {
case AES256:
case AES192:
case AES128:
if(protocol.cipher_mode == CBC) {
selected = 0;
} else {
selected = 1;
}
break;
case CHACHA20:
selected = 2;
break;
}
}
void Cryptography::Cipher::assign_iv(uint8_t *iv)
{
this->iv = iv;
}
void Cryptography::Cipher::assign_key(uint8_t *key)
{
this->key = key;
}
// void Cryptography::Decipher::Decryptor::operator()(AesDecryptorCBC_GMC auto &dec)
// {
// if(!init) {
// plaintext_length = ciphertext_length>>1;
// plaintext = new uint8_t[plaintext_length];
// }
// CryptoPP::StreamTransformationFilter filter(dec, new CryptoPP::ArraySink(plaintext, plaintext_length), CryptoPP::StreamTransformationFilter::NO_PADDING);
// filter.Put(ciphertext, ciphertext_length);
// filter.MessageEnd();
// init = true;
// }
//
// void Cryptography::Decipher::Decryptor::operator()(CryptoPP::ChaCha::Encryption &dec)
// {
// if(!init) {
// plaintext_length = ciphertext_length;
// plaintext = new uint8_t[plaintext_length];
// }
// dec.ProcessData(&plaintext[0], (const uint8_t*)ciphertext, ciphertext_length);
// init = true;
// }
Cryptography::Decipher::Decipher(ProtocolData &protocol, uint8_t *key) : protocol(protocol)
{
this->key = key; // no need to destroy key since it's not allocated here.
switch(protocol.cipher) {
case AES256:
case AES192:
case AES128:
if(protocol.cipher_mode == CBC) {
selected = 0;
} else {
selected = 1;
}
break;
case CHACHA20:
selected = 2;
break;
}
}
// cipher: output of protocol.get_decipher()
// ct: ciphertext
// ct_len: ciphertext length
// pt: plaintext
// length: pt length
// mac: only matters if AEAD algoritm (GCM)
// decrypts data, doesn't remove padding
void Cryptography::Decipher::decrypt(uint8_t *ct, uint64_t ct_len, uint8_t *pt, uint64_t length, uint8_t *mac)
{
switch(selected) {
case 0:
{
dec1.SetKeyWithIV(key, protocol.key_size, iv, protocol.iv_size);
dec1.ProcessData(pt, ct, length);
// CryptoPP::StreamTransformationFilter filter(dec1, new CryptoPP::ArraySink(pt, length), CryptoPP::StreamTransformationFilter::NO_PADDING);
// filter.Put(ct, ct_len);
// filter.MessageEnd();
}
break;
case 1:
{
dec2.SetKeyWithIV(key, protocol.key_size, iv, protocol.iv_size);
CryptoPP::AuthenticatedDecryptionFilter df(dec2, new CryptoPP::ArraySink(pt, length),
CryptoPP::AuthenticatedDecryptionFilter::MAC_AT_BEGIN,
protocol.mac_size,
CryptoPP::StreamTransformationFilter::NO_PADDING);
df.ChannelPut(CryptoPP::DEFAULT_CHANNEL, mac, protocol.mac_size);
df.ChannelPut(CryptoPP::AAD_CHANNEL, (const uint8_t*)"", 0);
df.ChannelPut(CryptoPP::DEFAULT_CHANNEL, ct, ct_len);
df.ChannelMessageEnd(CryptoPP::AAD_CHANNEL);
df.ChannelMessageEnd(CryptoPP::DEFAULT_CHANNEL);
verified_gcm = df.GetLastResult();
// CryptoPP::AuthenticatedDecryptionFilter filter(dec2, new CryptoPP::ArraySink(pt, length),
// CryptoPP::AuthenticatedDecryptionFilter::MAC_AT_BEGIN,
// protocol.mac_size, CryptoPP::StreamTransformationFilter::NO_PADDING);
// filter.Put(ct, ct_len);
// filter.MessageEnd();
}
break;
case 2:
dec3.SetKeyWithIV(key, protocol.key_size, iv, protocol.iv_size);
dec3.ProcessData(pt, ct, ct_len);
break;
}
}
// assign iv
void Cryptography::Decipher::assign_iv(uint8_t *iv)
{
this->iv = iv;
}
// assign key
void Cryptography::Decipher::assign_key(uint8_t *key)
{
this->key = key;
}
void Cryptography::Ecdsa::signer_init(auto signer, uint8_t *msg, uint16_t msg_len)
{
// Valgrind: still reachable memory leak (16 bytes). In stringsource code. Nothing can be done as it seems to an dismissable library bug.
signer.AccessKey().Initialize(protocol.curve_oid, key->private_key);
CryptoPP::StringSource s(msg, msg_len, true,
new CryptoPP::SignerFilter(prng,
signer,
new CryptoPP::ArraySink(signature, protocol.mac_size)));
}
Cryptography::Ecdsa& Cryptography::Ecdsa::operator=(Cryptography::Ecdsa &&other)
{
this->protocol = other.protocol;
this->key = other.key;
if(signature == nullptr)
signature = new uint8_t[protocol.mac_size];
memcpy(this->signature, other.signature, protocol.mac_size); // copy signature
this->verified = other.verified;
return *this;
}
Cryptography::Ecdsa::~Ecdsa()
{
if(signature != nullptr)
delete [] signature;
}
uint8_t *Cryptography::Ecdsa::get_signature()
{
return signature;
}
bool Cryptography::Ecdsa::is_verified()
{
return verified;
}
// msg: message as the data segment. If image, msg_len is IMAGE_BUFFER_SIZE
// msg_len: length of msg
Cryptography::Ecdsa::Ecdsa(ProtocolData &protocol, Key &key) : protocol(protocol), key(&key)
{
signature = new uint8_t[protocol.mac_size];
}
// returns signature as a vector
// msg: message to sign
// msg_len: length of message to sign
void Cryptography::Ecdsa::sign(uint8_t *msg, uint16_t msg_len)
{
if(protocol.hash == SHA256) {
CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA256>::Signer signer;
signer_init(signer, msg, msg_len);
} else if(protocol.hash == SHA512) {
CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA512>::Signer signer;
signer_init(signer, msg, msg_len);
} else {
#if DEBUG_MODE
throw std::runtime_error("Ecdsa::sign: HASHING_ALGORITHM_NOT_FOUND error. The protocol number is not valid");
#endif
error = HASHING_ALGORITHM_NOT_FOUND;
// give it the default value
CryptoPP::ECDSA<CryptoPP::ECP, default_hash>::Signer signer;
signer_init(signer, msg, msg_len);
}
}
// public key is received as bytes. Convert to ECPoint using: Key::reconstruct_point_from_bytes
// msg: message to verify
// msg_len: length of msg
// signature: ECDSA signature
// signature_len: length of signature
// public_key: received public key. Not the own public key
bool Cryptography::Ecdsa::verify(uint8_t *msg, uint16_t msg_len, uint8_t *&signature,
CryptoPP::ECPPoint public_key)
{
bool verified;
if(protocol.hash == SHA256) {
CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA256>::PublicKey public_k;
public_k.Initialize(protocol.curve_oid, public_key); // init public key
CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA256>::Verifier verifier(public_k);
verified = verifier.VerifyMessage(msg, msg_len, signature, protocol.mac_size); // ecdsa message verification
} else if(protocol.hash == SHA512) {
CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA512>::PublicKey public_k;
public_k.Initialize(protocol.curve_oid, public_key); // init public key
CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA512>::Verifier verifier(public_k);
verified = verifier.VerifyMessage(msg, msg_len, signature, protocol.mac_size); // ecdsa message verification
} else {
#if DEBUG_MODE
throw std::runtime_error("Ecdsa::verify: HASHING_ALGORITHM_NOT_FOUND error. The protocol number is not valid");
#endif
error = HASHING_ALGORITHM_NOT_FOUND;
// default hash value
CryptoPP::ECDSA<CryptoPP::ECP, default_hash>::PublicKey public_k;
public_k.Initialize(protocol.curve_oid, public_key); // init public key
CryptoPP::ECDSA<CryptoPP::ECP, default_hash>::Verifier verifier(public_k);
verified = verifier.VerifyMessage(msg, msg_len, signature, protocol.mac_size); // ecdsa message verification
}
this->verified = verified;
return verified;
}
// returns the length of out buffer, gets the compressed x value with the 03 starting byte
template<Cryptography::SupportedHashAlgs HashAlg>
uint16_t Cryptography::Ecdsa::get_compressed(CryptoPP::ECDSA<CryptoPP::ECP, HashAlg> &public_key, uint8_t *out_buffer)
{
CryptoPP::Integer x = public_key.GetPublicElement().x;
uint16_t bytes_len = x.MinEncodedSize(CryptoPP::Integer::UNSIGNED);
out_buffer = new uint8_t[bytes_len+1];
x.Encode(&out_buffer[1], bytes_len, CryptoPP::Integer::UNSIGNED);
out_buffer[0] = 0x03; // first byte is 03 to denote that it's compressed. When received public key, check if out_buffer is compressed then call get_decompressed
bytes_len++;
return bytes_len;
}
// public_key: 03 concatinated with x-coordinate of the public key
// public_key_len: length of public key
template<Cryptography::SupportedHashAlgs HashAlg>
CryptoPP::ECDSA<CryptoPP::ECP, HashAlg> Cryptography::Ecdsa::get_decompressed(uint8_t *public_key, uint16_t public_key_len)
{
typename CryptoPP::ECDSA<CryptoPP::ECP, HashAlg>::PublicKey public_k;
CryptoPP::ECPPoint point;
public_k.GetGroupParameters().GetCurve().DecodePoint(point, public_key, public_key_len);
public_k.SetPublicElement(point);
return public_k;
}
// generator initializer
// hmacf: hmac function
// pt: plaintext
// pt_len: plaintext length
void Cryptography::Hmac::generator_init(auto hmacf, uint8_t *ct, uint64_t pt_len)
{
hmacf.CalculateDigest(mac, ct, pt_len);
}
// mac member has to be initialized before calling
bool Cryptography::Hmac::verifier_init(auto hmacf, uint8_t *ct, uint64_t len, uint8_t *hmac)
{
hmacf.CalculateDigest(mac, ct, len);
// Compare the calculated HMAC with the expected HMAC
bool verified = memcmp(mac, hmac, protocol.mac_size) == 0;
return verified;
}
Cryptography::Hmac::Hmac(ProtocolData &protocol, uint8_t *key) : protocol(protocol)
{
this->key = key;
mac = new uint8_t[protocol.mac_size];
}
Cryptography::Hmac::~Hmac()
{
if(mac != nullptr) {
delete[] mac;
}
}
// get mac
uint8_t *Cryptography::Hmac::get_mac()
{
return mac;
}
// get if verified
bool Cryptography::Hmac::is_verified()
{
return verified;
}
// generate the HMAC code
void Cryptography::Hmac::generate(uint8_t *ct, uint64_t len)
{
if(protocol.hash == SHA256) {
CryptoPP::HMAC<CryptoPP::SHA256> hmac(key, protocol.key_size);
generator_init(hmac, ct, len);
} else if(protocol.hash == SHA512) {
CryptoPP::HMAC<CryptoPP::SHA512> hmac(key, protocol.key_size);
generator_init(hmac, ct, len);
} else {
#if DEBUG_MODE
throw std::runtime_error("Hmac::generate: HASHING_ALGORITHM_NOT_FOUND error. The protocol number is not valid");
#endif
error = HASHING_ALGORITHM_NOT_FOUND;
// default values
CryptoPP::HMAC<default_hash> hmac(key, protocol.key_size);
generator_init(hmac, ct, len);
}
}
// verify the HMAC code
bool Cryptography::Hmac::verify(uint8_t *ct, uint64_t len, uint8_t *mac_code)
{
if(protocol.hash == SHA256) {
CryptoPP::HMAC<CryptoPP::SHA256> hmac(key, protocol.key_size);
verified = verifier_init(hmac, ct, len, mac_code);
} else if(protocol.hash == SHA512) {
CryptoPP::HMAC<CryptoPP::SHA512> hmac(key, protocol.key_size);
verified = verifier_init(hmac, ct, len, mac_code);
} else {
#if DEBUG_MODE
throw std::runtime_error("Hmac::verify: HASHING_ALGORITHM_NOT_FOUND error. The protocol number is not valid");
#endif
error = HASHING_ALGORITHM_NOT_FOUND;
// default values
CryptoPP::HMAC<default_hash> hmac(key, protocol.key_size);
verified = verifier_init(hmac, ct, len, mac_code);
}
return verified;
}
Cryptography::Verifier::Verifier(ProtocolData &protocol, Key &key, Cipher *cipher=nullptr,
Decipher *decipher=nullptr) : protocol(protocol)
{
if (protocol.verifier == HMAC) {
hmac = new Hmac(protocol, key.key);
} else if (protocol.verifier == ECDSA) {
ecdsa = new Ecdsa(protocol, key);
} else { // GCM
mac = Cipher::to_uint8_ptr(cipher->get_mac_gcm()); // already generated
this->decipher = decipher;
#if DEBUG_MODE
if(decipher == nullptr && cipher == nullptr) {
throw std::runtime_error("Verifier::Verifier: DECIPHER NULL error. In GCM mode, decipher or cipher object has to be non-nullptr");
}
#endif
}
}
Cryptography::Verifier::~Verifier()
{
if(hmac != nullptr)
delete hmac;
if(ecdsa != nullptr)
delete ecdsa;
}
void Cryptography::Verifier::generate(uint8_t *ct=nullptr, uint64_t ct_len=0, uint8_t *pt=nullptr, uint64_t pt_len=0)
{
if (protocol.verifier == HMAC) {
hmac->generate(ct, ct_len); // hmac ciphertext
mac = hmac->get_mac();
} else if (protocol.verifier == ECDSA) {
ecdsa->sign(pt, pt_len); // sign plaintext
mac = ecdsa->get_signature();
}
// GCM generation not needed, defined in constructor
}
void Cryptography::Verifier::verify(uint8_t *ct=nullptr, uint64_t ct_len=0, uint8_t *pt=nullptr, uint64_t pt_len=0,
uint8_t *mac=nullptr, CryptoPP::ECPPoint *public_key=nullptr)
{
if (protocol.verifier == HMAC) {
hmac->verify(ct, ct_len, mac);
verified = hmac->is_verified();
} else if (protocol.verifier == ECDSA) {
ecdsa->verify(pt, pt_len, mac, *public_key);
verified = ecdsa->is_verified();
} else { // GCM
verified = decipher->is_verified_gcm();
}
}
bool Cryptography::Verifier::is_verified()
{
return verified;
}
uint8_t *Cryptography::Verifier::get_mac()
{
return mac;
}