-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcripter.cpp
executable file
·1608 lines (1240 loc) · 54.2 KB
/
cripter.cpp
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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*cripter.cpp*/
#include "cripter.h"
// =============== AES FUNCTION ===============
PackedByteArray Cripter::aes_encrypt(const PackedByteArray plaintext, const String p_password, PackedByteArray p_iv, Algorithm algorith, KeySize keybits){
PackedByteArray result = _aes_crypt(plaintext, p_password, p_iv, algorith, keybits, MBEDTLS_AES_ENCRYPT);
return result;
/*
std::vector<unsigned char> password = GDstring_to_STDvector(p_password);
std::vector<unsigned char> input = byteArray_to_vector(plaintext);
std::vector<unsigned char> iv = byteArray_to_vector(p_iv);
std::vector<unsigned char> result = _aes_crypt(input, password, iv, algorith, keybits, MBEDTLS_AES_ENCRYPT);
PackedByteArray ret;
ret.resize(result.size());
memcpy(ret.ptrw(), result.data(), result.size());
return ret;
*/
}
PackedByteArray Cripter::aes_decrypt(const PackedByteArray ciphertext, const String p_password, PackedByteArray p_iv, Algorithm algorith, KeySize keybits){
PackedByteArray result = _aes_crypt(ciphertext, p_password, p_iv, algorith, keybits, MBEDTLS_AES_DECRYPT);
return result;
/*
std::vector<unsigned char> password = GDstring_to_STDvector(p_password);
std::vector<unsigned char> input = byteArray_to_vector(ciphertext);
std::vector<unsigned char> iv = byteArray_to_vector(p_iv);
std::vector<unsigned char> result = _aes_crypt(input, password, iv, algorith, keybits, MBEDTLS_AES_DECRYPT);
PackedByteArray ret;
ret.resize(result.size());
memcpy(ret.ptrw(), result.data(), result.size());
return ret;
*/
}
PackedByteArray Cripter::_aes_crypt(PackedByteArray input, String password, PackedByteArray iv, Algorithm algorith, Cripter::KeySize keybits, int mode){
//std::vector<unsigned char> Cripter::_aes_crypt(std::vector<unsigned char> input, std::vector<unsigned char> password, std::vector<unsigned char> iv, Algorithm algorith, Cripter::KeySize keybits, int mode){
if ((keybits < BITS_128)){
WARN_PRINT("Most AES algorithms support 128,192 and 256 bits keys, with the exception of XTS, which only supports 256 and 512 bits keys. - Using 128 Bits key size");
keybits = BITS_128;
}
else if (keybits > BITS_256){
WARN_PRINT("Most AES algorithms support 128,192 and 256 bits keys, with the exception of XTS, which only supports 256 and 512 bits keys. - Using 256 Bits key size");
keybits = BITS_256;
}
/*
if ((algorith != XTS) and (keybits < BITS_128)){
WARN_PRINT("Most AES algorithms support 128,192 and 256 bits keys, with the exception of XTS, which only supports 256 and 512 bits keys. - Using 128 Bits key size");
keybits = BITS_128;
}
else if (algorith != XTS and keybits > BITS_256){
WARN_PRINT("Most AES algorithms support 128,192 and 256 bits keys, with the exception of XTS, which only supports 256 and 512 bits keys. - Using 256 Bits key size");
keybits = BITS_256;
}
else if (algorith == XTS and keybits < BITS_256){
WARN_PRINT("XTS algorithm support only supports 256 and 512 bits keys. - Using 256 Bits key size");
keybits = BITS_256;
}
else if (algorith == XTS and keybits > BITS_512){
WARN_PRINT("XTS algorithm support only supports 256 and 512 bits keys. - Using 512 Bits key size");
keybits = BITS_512;
}
*/
// std::vector<unsigned char> output;
PackedByteArray output;
if (iv.size() != AES_GCM_BLOCK_SIZE){
WARN_PRINT("The IV size must be AES_BLOCK_SIZE for AES encryption.");
return output;
}
int mbedtls_erro;
mbedtls_aes_context aes_ctx;
mbedtls_aes_init(&aes_ctx);
output.resize(input.size());
// mbedtls_erro = mbedtls_aes_setkey_enc(&aes_ctx, password.data(), keybits);
mbedtls_erro = mbedtls_aes_setkey_enc(&aes_ctx, reinterpret_cast<const unsigned char*>(password.utf8().get_data()), keybits);
if (mbedtls_erro != OK){
mbedtls_aes_free(&aes_ctx);
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_aes_setkey_enc");
WARN_PRINT(String("Failed to configure AES key.: -0x") + String::num_int64(-mbedtls_erro, 16) + _err);
return output;
};
switch (algorith) {
case EBC: {
//mbedtls_erro = mbedtls_aes_crypt_ecb(&aes_ctx, mode, input.data(), output.data());
mbedtls_erro = mbedtls_aes_crypt_ecb(&aes_ctx, mode, input.ptr(), output.ptrw());
mbedtls_aes_free(&aes_ctx);
if (mbedtls_erro != OK){
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_aes_crypt_ecb");
WARN_PRINT(String("EBC Encryption error: -0x%04x\n") + String::num_int64(-mbedtls_erro, 16) + _err);
}
return output;
}
break;
case CBC: {
if (mode == MBEDTLS_AES_ENCRYPT){
/*
if (add_pkcs7_padding(input, input, AES_GCM_BLOCK_SIZE) != OK){
WARN_PRINT(String("Invalid parameter. AES block must be 16 Bytes."));
mbedtls_aes_free(&aes_ctx);
return output;
}
*/
input = add_pkcs7_padding(input, AES_GCM_BLOCK_SIZE);
}
// unsigned char iv_copy[16];
// memcpy(iv_copy, iv.data(), 16);
PackedByteArray iv_copy = iv.duplicate();
//mbedtls_erro = mbedtls_aes_crypt_cbc(&aes_ctx, mode, input.size(), iv_copy, input.data(), output.data());
mbedtls_erro = mbedtls_aes_crypt_cbc(&aes_ctx, mode, input.size(), iv_copy.ptrw(), input.ptr(), output.ptrw());
if (mbedtls_erro != OK){
mbedtls_aes_free(&aes_ctx);
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_aes_crypt_cbc");
WARN_PRINT(String("CBC Encryption error: -0x%04x\n") + String::num_int64(-mbedtls_erro, 16) + _err);
return output;
}
if (mode == MBEDTLS_AES_DECRYPT){
/*
Error _err = remove_pkcs7_padding(output, output, AES_GCM_BLOCK_SIZE);
if ( _err == ERR_INVALID_PARAMETER){
WARN_PRINT("Block size out of parameter.");
}
else if(_err == ERR_INVALID_DATA){
WARN_PRINT(String("Input buffer contains invalid Padding."));
}
*/
output = remove_pkcs7_padding(output, AES_GCM_BLOCK_SIZE);
}
return output;
}
break;
case CFB128:{
// unsigned char iv_copy[16];
// memcpy(iv_copy, iv.data(), 16);
size_t iv_off = 0;
PackedByteArray iv_copy = iv.duplicate();
// mbedtls_erro = mbedtls_aes_crypt_cfb128(&aes_ctx, mode, input.size(), &iv_off, iv_copy, input.data(), output.data());
mbedtls_erro = mbedtls_aes_crypt_cfb128(&aes_ctx, mode, input.size(), &iv_off, iv_copy.ptrw(), input.ptr(), output.ptrw());
mbedtls_aes_free(&aes_ctx);
if (mbedtls_erro != OK){
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_aes_crypt_cfb128");
WARN_PRINT(String("CFB128 Encryption error: -0x%04x\n") + String::num_int64(-mbedtls_erro, 16) + _err);
}
return output;
}
break;
case CFB8:{
// unsigned char iv_copy[16];
// memcpy(iv_copy, iv.data(), 16);
PackedByteArray iv_copy = iv.duplicate();
mbedtls_erro = mbedtls_aes_crypt_cfb8(&aes_ctx, mode, input.size(), iv_copy.ptrw(), input.ptr(), output.ptrw());
mbedtls_aes_free(&aes_ctx);
if (mbedtls_erro != OK){
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_aes_crypt_cfb8");
WARN_PRINT(String("CFB8 Encryption error: -0x%04x\n") + String::num_int64(-mbedtls_erro, 16) + _err);
}
return output;
}
break;
case OFB:{
// unsigned char iv_copy[16];
// memcpy(iv_copy, iv.data(), 16);
PackedByteArray iv_copy = iv.duplicate();
size_t iv_off = 0;
mbedtls_erro = mbedtls_aes_crypt_ofb(&aes_ctx, input.size(), &iv_off, iv_copy.ptrw(), input.ptr(), output.ptrw());
mbedtls_aes_free(&aes_ctx);
if (mbedtls_erro != OK){
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_aes_crypt_ofb");
WARN_PRINT(String("OFB Encryption error: -0x%04x\n") + String::num_int64(-mbedtls_erro, 16) + _err);
}
return output;
}
break;
case CTR: {
size_t nc_off = 0;
PackedByteArray nonce_counter = iv.duplicate();
PackedByteArray stream_block;
stream_block.resize(AES_GCM_BLOCK_SIZE);
stream_block.fill(0);
mbedtls_erro = mbedtls_aes_crypt_ctr(&aes_ctx, input.size(), &nc_off, nonce_counter.ptrw(), stream_block.ptrw(), input.ptr(), output.ptrw());
mbedtls_aes_free(&aes_ctx);
if (mbedtls_erro != OK){
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_aes_crypt_ctr");
WARN_PRINT(String("CTR Encryption error: -0x%04x\n") + String::num_int64(-mbedtls_erro, 16) + _err);
}
return output;
}
break;
/*
case CTR: {
// unsigned char nonce_counter[16];
// memcpy(nonce_counter, iv.data(), 16);
// unsigned char stream_block[16];
// memset(stream_block, 0, 16);
size_t nc_off = 0;
PackedByteArray nonce_counter = iv.duplicate();
PackedByteArray stream_block;
stream_block.resize(AES_GCM_BLOCK_SIZE);
stream_block.fill(0);
mbedtls_erro = mbedtls_aes_crypt_ctr(&aes_ctx, input.size(), &nc_off, nonce_counter.ptrw(), stream_block.ptrw(), input.ptr(), output.ptrw());
mbedtls_aes_free(&aes_ctx);
if (mbedtls_erro != OK){
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_aes_crypt_ctr");
WARN_PRINT(String("CTR Encryption error: -0x%04x\n") + String::num_int64(-mbedtls_erro, 16) + _err);
}
return output;
}
break;
*/
}; // switch case
return output;
}
// Error Cripter::aes_start_stream(const String password){}
// Error Cripter::aes_update_stream(const PackedByteArray data){}
// Error Cripter::aes_stop_stream(){}
// =============== GCM FUNCTION ===============
Dictionary Cripter::gcm_encrypt(const PackedByteArray plaintext, const String p_password, const PackedByteArray p_iv, String p_aad, Cripter::KeySize keybits){
std::vector<unsigned char> password = GDstring_to_STDvector(p_password);
std::vector<unsigned char> input = byteArray_to_vector(plaintext);
std::vector<unsigned char> aad = GDstring_to_STDvector(p_aad);
std::vector<unsigned char> iv = byteArray_to_vector(p_iv);
std::vector<unsigned char> tag(GCM_TAG_SIZE);
Dictionary ret = _gcm_crypt(input, password, iv, aad, tag, keybits, MBEDTLS_GCM_ENCRYPT);
return ret;
}
PackedByteArray Cripter::gcm_decrypt(const PackedByteArray ciphertext, const String p_password, const PackedByteArray p_iv, const PackedByteArray p_tag, String p_aad, Cripter::KeySize keybits){
ERR_FAIL_COND_V_MSG(p_tag.size() != 16, PackedByteArray(), "Tags for GCM encryption must have the default value of 16.");
std::vector<unsigned char> password = GDstring_to_STDvector(p_password);
std::vector<unsigned char> input = byteArray_to_vector(ciphertext);
std::vector<unsigned char> aad = GDstring_to_STDvector(p_aad);
std::vector<unsigned char> tag = byteArray_to_vector(p_tag);
std::vector<unsigned char> iv = byteArray_to_vector(p_iv);
PackedByteArray ret = _gcm_crypt(input, password, iv, aad, tag, keybits, MBEDTLS_GCM_DECRYPT);
return ret;
}
Variant Cripter::_gcm_crypt(
std::vector<unsigned char> input,
std::vector<unsigned char> password,
std::vector<unsigned char> iv,
std::vector<unsigned char> aad,
std::vector<unsigned char> tag,
Cripter::KeySize keybits,
int mode
){
if (keybits < BITS_128){
WARN_PRINT("GCM Algorithm only accepts key with 128, 192, or 256 bits");
keybits = BITS_128;
}
if (keybits > BITS_256){
WARN_PRINT("GCM Algorithm only accepts key with 128, 192, or 256 bits");
keybits = BITS_256;
}
mbedtls_gcm_context gcm_ctx;
mbedtls_gcm_init(&gcm_ctx);
PackedByteArray output;
output.resize(input.size());
int mbedtls_erro = mbedtls_gcm_setkey(&gcm_ctx, MBEDTLS_CIPHER_ID_AES, password.data(), keybits);
if (mbedtls_erro != OK) {
mbedtls_gcm_free(&gcm_ctx);
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_gcm_setkey");
ERR_FAIL_V_EDMSG(Dictionary(), String("Failed to configure GCM key.: -0x") + String::num_int64(-mbedtls_erro, 16) + _err);
}
mbedtls_erro = mbedtls_gcm_crypt_and_tag(
&gcm_ctx, mode, input.size(),
iv.data(), iv.size(),
aad.data(), aad.size(),
input.data(), output.ptrw(),
GCM_TAG_SIZE, tag.data()
);
mbedtls_gcm_free(&gcm_ctx);
if (mbedtls_erro != OK) {
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_gcm_crypt_and_tag");
ERR_FAIL_V_EDMSG(Dictionary(), String("Encryption error. : -0x") + String::num_int64(-mbedtls_erro, 16) + _err);
}
PackedByteArray tag_array;
tag_array.resize(GCM_TAG_SIZE);
memcpy(tag_array.ptrw(), tag.data(), GCM_TAG_SIZE);
Dictionary ret;
ret["Tag"] = tag_array;
ret["Ciphertext"] = output;
return ret;
}
// Stream
Error Cripter::gcm_start_stream(const String password, const PackedByteArray iv, const CryptMode mode, Cripter::KeySize keybits){
if (gcm_stream != nullptr){
mbedtls_gcm_free(&gcm_stream->gcm_ctx);
delete gcm_stream;
gcm_stream = nullptr;
}
gcm_stream = new gcm_streamer();
mbedtls_gcm_init(&gcm_stream->gcm_ctx);
int mbedtls_erro;
const unsigned char *key = reinterpret_cast<const unsigned char*>(password.utf8().get_data());
if (keybits < BITS_128){
WARN_PRINT("GCM Algorithm only accepts key with 128, 192, or 256 bits");
keybits = BITS_128;
}
if (keybits > BITS_256){
WARN_PRINT("GCM Algorithm only accepts key with 128, 192, or 256 bits");
keybits = BITS_256;
}
mbedtls_erro = mbedtls_gcm_setkey(&gcm_stream->gcm_ctx, MBEDTLS_CIPHER_ID_AES, key, keybits);
if (mbedtls_erro != OK) {
mbedtls_gcm_free(&gcm_stream->gcm_ctx);
delete gcm_stream;
gcm_stream = nullptr;
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_gcm_setkey");
ERR_FAIL_V_EDMSG(FAILED, String("Failed to configure GCM key.: -0x") + String::num_int64(-mbedtls_erro, 16) + _err);
}
mbedtls_erro = mbedtls_gcm_starts(&gcm_stream->gcm_ctx, (int)mode, iv.ptr(), iv.size());
if (mbedtls_erro != OK) {
mbedtls_gcm_free(&gcm_stream->gcm_ctx);
delete gcm_stream;
gcm_stream = nullptr;
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_gcm_starts");
ERR_FAIL_V_EDMSG(FAILED, String("Failed to set the streamer.: -0x") + String::num_int64(-mbedtls_erro, 16) + _err);
}
return OK;
}
PackedByteArray Cripter::gcm_update_stream(const PackedByteArray data, const bool in_chunk){
PackedByteArray output;
int mbedtls_erro;
size_t plaintext_len = data.size();
output.resize(plaintext_len + AES_GCM_BLOCK_SIZE);
size_t output_len = 0;
if (in_chunk){
size_t chunk_size = AES_GCM_BLOCK_SIZE;
size_t offset = 0;
while (offset < plaintext_len) {
size_t len = (plaintext_len - offset > chunk_size) ? chunk_size : (plaintext_len - offset);
mbedtls_erro = mbedtls_gcm_update(
&gcm_stream->gcm_ctx,
data.ptr() + offset, len,
output.ptrw() + offset,
offset,
&output_len
);
if (mbedtls_erro != OK) {
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_gcm_update");
ERR_FAIL_V_EDMSG(PackedByteArray(), String("Failed to perform GCM stream operation.: -0x") + String::num_int64(-mbedtls_erro, 16) + _err);
}
offset += len;
}
}else{
mbedtls_erro = mbedtls_gcm_update(&gcm_stream->gcm_ctx, data.ptr(), plaintext_len, output.ptrw(), plaintext_len, &plaintext_len);
if (mbedtls_erro != OK) {
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_gcm_update");
ERR_FAIL_V_EDMSG(PackedByteArray(), String("Failed to perform GCM stream operation.: -0x") + String::num_int64(-mbedtls_erro, 16) + _err);
}
}
return output;
}
PackedByteArray Cripter::gcm_stop_stream(PackedByteArray data){
PackedByteArray tag;
tag.resize(GCM_TAG_SIZE);
size_t tag_size = GCM_TAG_SIZE;
int mbedtls_erro = mbedtls_gcm_finish(&gcm_stream->gcm_ctx, data.ptrw(), (size_t)data.size(), &tag_size, tag.ptrw(), tag.size());
if(mbedtls_erro != OK){
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_gcm_update");
String err_msn = String("Failed to perform GCM stream operation.: -0x") + String::num_int64(-mbedtls_erro, 16) + _err;
WARN_PRINT(err_msn);
}
mbedtls_gcm_free(&gcm_stream->gcm_ctx);
delete gcm_stream;
gcm_stream = nullptr;
return tag;
}
// =============== ASYMMETRIC ===============
//TODO criptografar a chave
PackedStringArray Cripter::get_available_curves() {
PackedStringArray curve_names;
const mbedtls_ecp_curve_info* curve_info = mbedtls_ecp_curve_list();
while (curve_info != NULL && curve_info->name != NULL) {
curve_names.append(String(curve_info->name));
curve_info++;
}
return curve_names;
}
Error Cripter::pk_generate_keys(
PK_TYPE algorithm_type,
Cripter::KeySize key_size,
const ECP_GROUP_ID curve,
FileFormat storage_format,
const String password,
const String p_private_key_filename,
const String p_public_key_filename,
const String personalization
) {
// Create Variables
//unsigned char pri_output_buf[16000];
//unsigned char pub_output_buf[16000];
//std::vector<unsigned char> pri_output_buf(16000, 0);
//std::vector<unsigned char> pub_output_buf(16000, 0);
PackedByteArray pri_output_buf;
PackedByteArray pub_output_buf;
pri_output_buf.resize(16000);
pub_output_buf.resize(16000);
int pk_key_type;
int mbedtls_erro = 0;
const char* pers = personalization.utf8().get_data();
mbedtls_pk_type_t algorithm = static_cast<mbedtls_pk_type_t>(algorithm_type);
mbedtls_pk_context pk_key;
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
// Init Variables
//memset(pri_output_buf, 0, sizeof(pri_output_buf));
//memset(pub_output_buf, 0, sizeof(pub_output_buf));
mbedtls_pk_init(&pk_key);
mbedtls_entropy_init(&entropy);
mbedtls_ctr_drbg_init(&ctr_drbg);
String private_key_filename = ensure_global_path(p_private_key_filename);
String public_key_filename = ensure_global_path(p_public_key_filename);
if (algorithm == MBEDTLS_PK_ECKEY || algorithm == MBEDTLS_PK_ECKEY_DH || algorithm == MBEDTLS_PK_ECDSA) {
pk_key_type = TYPE_ECC;
}
else if (algorithm == MBEDTLS_PK_RSA || algorithm == MBEDTLS_PK_RSA_ALT || algorithm == MBEDTLS_PK_RSASSA_PSS){
pk_key_type = TYPE_RSA;
}
if (key_size < BITS_1024){
WARN_PRINT("RSA keys support sizes from 1024 to 8192 bits. - Using 1024 Bits key size");
key_size = BITS_1024;
}
else if (key_size > BITS_8192){
WARN_PRINT("RSA keys support sizes from 1024 to 8192 bits. - Using 8192 Bits key size");
key_size = BITS_8192;
}
// ENTROPY SEED
mbedtls_erro = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, reinterpret_cast<const unsigned char*>(pers), strlen(pers));
if (mbedtls_erro != OK) {
mbedtls_pk_free(&pk_key);
mbedtls_entropy_free(&entropy);
mbedtls_ctr_drbg_free(&ctr_drbg);
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_ctr_drbg_seed");
ERR_FAIL_V_EDMSG(FAILED, String("Failed to seed the random generator: -0x") + String::num_int64(-mbedtls_erro, 16) + _err);
}
const mbedtls_pk_info_t *pk_type = mbedtls_pk_info_from_type((mbedtls_pk_type_t) algorithm);
if (pk_type == NULL) {
mbedtls_pk_free(&pk_key);
mbedtls_entropy_free(&entropy);
mbedtls_ctr_drbg_free(&ctr_drbg);
ERR_FAIL_V_EDMSG(FAILED, "Invalid PK type info.");
}
mbedtls_erro = mbedtls_pk_setup(&pk_key, pk_type);
if (mbedtls_erro != OK) {
mbedtls_pk_free(&pk_key);
mbedtls_entropy_free(&entropy);
mbedtls_ctr_drbg_free(&ctr_drbg);
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_pk_setup");
ERR_FAIL_V_EDMSG(FAILED, String("Failed to Initialize a PK context: -0x") + String::num_int64(-mbedtls_erro, 16) + _err);
}
// ===================================== RSA =====================================
if (pk_key_type == TYPE_RSA){
mbedtls_erro = mbedtls_rsa_gen_key(mbedtls_pk_rsa(pk_key), mbedtls_ctr_drbg_random, &ctr_drbg, (unsigned int)key_size, EXPONENT);
if (mbedtls_erro != OK) {
mbedtls_pk_free(&pk_key);
mbedtls_entropy_free(&entropy);
mbedtls_ctr_drbg_free(&ctr_drbg);
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_rsa_gen_key");
ERR_FAIL_V_EDMSG(FAILED, String("Failed to create RSA key pair.: -0x") + String::num_int64(-mbedtls_erro, 16) + _err);
}
}
// ===================================== ECC =====================================
else if (pk_key_type == TYPE_ECC){
mbedtls_erro = mbedtls_ecp_gen_key((mbedtls_ecp_group_id)algorithm, mbedtls_pk_ec(pk_key), mbedtls_ctr_drbg_random, &ctr_drbg);
if (mbedtls_erro != OK) {
mbedtls_pk_free(&pk_key);
mbedtls_entropy_free(&entropy);
mbedtls_ctr_drbg_free(&ctr_drbg);
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_ecp_gen_key");
ERR_FAIL_V_EDMSG(FAILED, String("Failed to create ECP key pair.: -0x") + String::num_int64(-mbedtls_erro, 16) + _err);
}
}
// =================================== INVALID ====================================
else {
WARN_PRINT("Unsupported key type");
return ERR_INVALID_PARAMETER;
}
// Export keys ====
// PEM
if (storage_format == PEM){
mbedtls_erro = mbedtls_pk_write_key_pem(&pk_key, pri_output_buf.ptrw(), pri_output_buf.size());
if (mbedtls_erro != OK){
mbedtls_pk_free(&pk_key);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
ERR_FAIL_V_MSG(FAILED, mbed_error_msn(mbedtls_erro, "mbedtls_pk_write_key_pem"));
}
mbedtls_erro = mbedtls_pk_write_pubkey_pem(&pk_key, pub_output_buf.ptrw(), pub_output_buf.size());
if (mbedtls_erro != OK){
mbedtls_pk_free(&pk_key);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
ERR_FAIL_V_MSG(FAILED, mbed_error_msn(mbedtls_erro, "mbedtls_pk_write_pubkey_pem"));
}
}
// DER
else if (storage_format == DER){
mbedtls_erro = mbedtls_pk_write_key_der(&pk_key, pri_output_buf.ptrw(), pri_output_buf.size());
if (mbedtls_erro != OK){
mbedtls_pk_free(&pk_key);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
ERR_FAIL_V_MSG(FAILED, mbed_error_msn(mbedtls_erro, "mbedtls_pk_write_key_pem"));
}
mbedtls_erro = mbedtls_pk_write_pubkey_der(&pk_key, pub_output_buf.ptrw(), pub_output_buf.size());
if (mbedtls_erro != OK){
mbedtls_pk_free(&pk_key);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
ERR_FAIL_V_MSG(FAILED, mbed_error_msn(mbedtls_erro, "mbedtls_pk_write_pubkey_pem"));
}
}
// Encrypt key
if (not password.is_empty()){
PackedByteArray iv = generate_iv(AES_GCM_BLOCK_SIZE, String("Encrypt PKey"));
String derivated_key = derive_key_pbkdf2(password, password.sha256_text());
pri_output_buf = _aes_crypt(pri_output_buf, derivated_key, iv, CBC, BITS_256, MBEDTLS_AES_ENCRYPT);
}
// WRITE FILES
// Private
Ref<FileAccess> f_private = FileAccess::open(private_key_filename, FileAccess::WRITE);
ERR_FAIL_COND_V_MSG(f_private.is_null(), ERR_INVALID_PARAMETER, "Cannot save private RSA key to file: '" + private_key_filename + "'.");
// size_t pri_len = strlen((char *)pri_output_buf);
// f_private->store_buffer(pri_output_buf, pri_len);
// mbedtls_platform_zeroize(pri_output_buf, sizeof(pri_output_buf));
f_private->store_buffer(pri_output_buf);
pri_output_buf.fill(0); //zeroize
// Public
Ref<FileAccess> f_public = FileAccess::open(public_key_filename, FileAccess::WRITE);
ERR_FAIL_COND_V_MSG(f_public.is_null(), ERR_INVALID_PARAMETER, "Cannot save public RSA key to file: '" + public_key_filename + "'.");
// size_t pub_len = strlen((char *)pub_output_buf);
// f_public->store_buffer(pub_output_buf, pub_len);
// mbedtls_platform_zeroize(pub_output_buf, sizeof(pub_output_buf));
f_private->store_buffer(pub_output_buf);
pub_output_buf.fill(0); //zeroize
// Clean up
mbedtls_pk_free(&pk_key);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
return OK;
}
Variant Cripter::pk_match_keys(const String p_private_key_path, const String p_public_key_path, const String password){
const String private_key_path = ensure_global_path(p_private_key_path);
const String public_key_path = ensure_global_path(p_public_key_path);
int mbedtls_erro;
const char *pers = "pk_match_keys";
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_pk_context private_ctx, public_ctx;
mbedtls_pk_init(&private_ctx);
mbedtls_pk_init(&public_ctx);
mbedtls_entropy_init(&entropy);
mbedtls_ctr_drbg_init(&ctr_drbg);
mbedtls_erro = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, reinterpret_cast<const unsigned char*>(pers), strlen(pers));
if (mbedtls_erro != OK) {
mbedtls_pk_free(&private_ctx);
mbedtls_pk_free(&public_ctx);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_ctr_drbg_seed");
ERR_FAIL_V_EDMSG(mbedtls_erro, String("Failed to seed random number generator: -0x") + String::num_int64(-mbedtls_erro, 16) + _err);
}
if (password.is_empty()){
mbedtls_erro = mbedtls_pk_parse_keyfile(&private_ctx, private_key_path.utf8().get_data(), nullptr, mbedtls_ctr_drbg_random, &ctr_drbg);
}else{
mbedtls_erro = mbedtls_pk_parse_keyfile(&private_ctx, private_key_path.utf8().get_data(), password.utf8().get_data(), mbedtls_ctr_drbg_random, &ctr_drbg);
}
if (mbedtls_erro != OK) {
mbedtls_pk_free(&private_ctx);
mbedtls_pk_free(&public_ctx);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_pk_parse_keyfile");
ERR_FAIL_V_EDMSG(mbedtls_erro, String("Error parsing private key.: -0x") + String::num_int64(-mbedtls_erro, 16) + _err);
}
mbedtls_erro = mbedtls_pk_parse_public_keyfile(&public_ctx, public_key_path.utf8().get_data());
if (mbedtls_erro != OK) {
mbedtls_pk_free(&private_ctx);
mbedtls_pk_free(&public_ctx);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_pk_parse_public_keyfile");
ERR_FAIL_V_EDMSG(mbedtls_erro, String("Error parsing public key.: -0x") + String::num_int64(-mbedtls_erro, 16) + _err);
}
mbedtls_erro = mbedtls_pk_check_pair(&public_ctx, &private_ctx, mbedtls_ctr_drbg_random, &ctr_drbg);
mbedtls_pk_free(&private_ctx);
mbedtls_pk_free(&public_ctx);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
if (mbedtls_erro != OK) {
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_pk_parse_public_keyfile");
ERR_FAIL_V_EDMSG(mbedtls_erro, String("Error parsing public key.: -0x") + String::num_int64(-mbedtls_erro, 16) + _err);
}
if (mbedtls_erro == OK){
return true;
}
return mbedtls_erro;
}
Dictionary Cripter::pk_analyze_key(const String p_key_path) {
Dictionary ret;
int mbedtls_error = 0;
const char *pers = "pk_parse_key";
String key_path = ensure_global_path(p_key_path);
mbedtls_pk_context pk;
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_pk_init(&pk);
mbedtls_entropy_init(&entropy);
mbedtls_ctr_drbg_init(&ctr_drbg);
mbedtls_error = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, reinterpret_cast<const unsigned char*>(pers), strlen(pers));
if (mbedtls_error != OK) {
mbedtls_pk_free(&pk);
mbedtls_entropy_free(&entropy);
mbedtls_ctr_drbg_free(&ctr_drbg);
String _err = mbed_error_msn(mbedtls_error, "mbedtls_ctr_drbg_seed");
ERR_FAIL_V_EDMSG(ret, String("Failed to seed random number generator: -0x") + String::num_int64(-mbedtls_error, 16) + _err);
}
// Try to load as private key
//const char *key_path = p_key_path.utf8().get_data();
mbedtls_error = mbedtls_pk_parse_keyfile(&pk, key_path.utf8().get_data(), nullptr, mbedtls_ctr_drbg_random, &ctr_drbg);
bool is_private = false;
// Determines whether it is a public or private key.
if (mbedtls_error != OK) {
// Try to load as public key
mbedtls_error = mbedtls_pk_parse_public_keyfile(&pk, key_path.utf8().get_data());
if (mbedtls_error != OK) {
mbedtls_pk_free(&pk);
mbedtls_entropy_free(&entropy);
mbedtls_ctr_drbg_free(&ctr_drbg);
String _err = mbed_error_msn(mbedtls_error, "mbedtls_pk_parse_public_keyfile");
ERR_FAIL_V_EDMSG(ret, String("Failed to parse public keyfile.: -0x") + String::num_int64(-mbedtls_error, 16) + _err);
}
ret["CATEGORY"] = "PUBLIC";
} else {
ret["CATEGORY"] = "PRIVATE";
is_private = true;
}
// Get the key type and name
mbedtls_pk_type_t pk_type = mbedtls_pk_get_type(&pk);
const char *pk_name = mbedtls_pk_get_name(&pk);
ret["NAME"] = String(pk_name);
// Get the key size in bytes and bits
ret["LENGTH"] = (int)mbedtls_pk_get_len(&pk);
ret["BITS_LENGTH"] = (int)mbedtls_pk_get_bitlen(&pk);
// Key Type
mbedtls_pk_type_t key_type = mbedtls_pk_get_type(&pk);
ret["TYPE"] = static_cast<PK_TYPE>(key_type);
//====================================== ECP ====================================================
if (
static_cast<mbedtls_pk_type_t>(pk_type) == mbedtls_pk_type_t::MBEDTLS_PK_ECKEY ||
static_cast<mbedtls_pk_type_t>(pk_type) == mbedtls_pk_type_t::MBEDTLS_PK_ECKEY_DH ||
static_cast<mbedtls_pk_type_t>(pk_type) == mbedtls_pk_type_t::MBEDTLS_PK_ECDSA
){
// Get EC Context
mbedtls_ecp_keypair *ec_key = mbedtls_pk_ec(pk);
if (ec_key == NULL) {
mbedtls_pk_free(&pk);
mbedtls_entropy_free(&entropy);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_ecp_keypair_free(ec_key);
String _err = mbed_error_msn(mbedtls_error, "mbedtls_pk_ec");
ERR_FAIL_V_EDMSG(ret, String("Invalid ECP Context: -0x") + String::num_int64(-mbedtls_error, 16) + _err);
}
// Get courve Info
mbedtls_ecp_group *ecp_group = &ec_key->private_grp;
mbedtls_ecp_curve_type curve_type = mbedtls_ecp_get_type(ecp_group);
ret["CURVE_TYPE"] = curve_type;
mbedtls_ecp_group_id grp_id = mbedtls_ecp_keypair_get_group_id(ec_key);
const mbedtls_ecp_curve_info *curve_info = mbedtls_ecp_curve_info_from_grp_id(grp_id);
if (curve_info != NULL) {
ret["CURVE"] = String(curve_info->name);
} else {
ret["CURVE"] = "Unknown";
}
if (is_private){
mbedtls_error = mbedtls_ecp_check_privkey(&ec_key->private_grp, &ec_key->private_d);
if (mbedtls_error != OK) {
mbedtls_pk_free(&pk);
mbedtls_entropy_free(&entropy);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_ecp_keypair_free(ec_key);
String _err = mbed_error_msn(mbedtls_error, "mbedtls_ecp_check_pubkey");
ERR_FAIL_V_EDMSG(ret, String("Invalid EC private point: -0x") + String::num_int64(-mbedtls_error, 16) + _err);
}
}
else{
mbedtls_error = mbedtls_ecp_check_pubkey(&ec_key->private_grp, &ec_key->private_Q);
if (mbedtls_error != OK) {
mbedtls_pk_free(&pk);
mbedtls_entropy_free(&entropy);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_ecp_keypair_free(ec_key);
String _err = mbed_error_msn(mbedtls_error, "mbedtls_ecp_check_pubkey");
ERR_FAIL_V_EDMSG(ret, String("Invalid EC public point: -0x") + String::num_int64(-mbedtls_error, 16) + _err);
}
}
// Get the X and Y coordinates
mbedtls_mpi X, Y;
mbedtls_mpi_init(&X);
mbedtls_mpi_init(&Y);
mbedtls_mpi_copy(&X, &ec_key->private_Q.private_X);
mbedtls_mpi_copy(&Y, &ec_key->private_Q.private_Y);
// Convert X and Y to hexadecimal strings
char buffer[8192];
size_t n;
mbedtls_mpi_write_string(&X, 16, buffer, sizeof(buffer), &n);
ret["X"] = String(buffer);
mbedtls_mpi_write_string(&Y, 16, buffer, sizeof(buffer), &n);
ret["Y"] = String(buffer);
if (is_private) {
// Get the private key 'd'
mbedtls_mpi_write_string(&ec_key->private_d, 16, buffer, sizeof(buffer), &n);
ret["d"] = String(buffer);
}
// Cleaning
mbedtls_mpi_free(&X);
mbedtls_mpi_free(&Y);
mbedtls_ecp_keypair_free(ec_key);
//====================================== RSA ====================================================
} else if (
static_cast<mbedtls_pk_type_t>(pk_type) == mbedtls_pk_type_t::MBEDTLS_PK_RSA ||
static_cast<mbedtls_pk_type_t>(pk_type) == mbedtls_pk_type_t::MBEDTLS_PK_RSA_ALT ||
static_cast<mbedtls_pk_type_t>(pk_type) == mbedtls_pk_type_t::MBEDTLS_PK_RSASSA_PSS
) {
// Get RSA Context
mbedtls_rsa_context *rsa = mbedtls_pk_rsa(pk);
if (rsa == NULL) {
mbedtls_pk_free(&pk);
mbedtls_entropy_free(&entropy);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_rsa_free(rsa);
String _err = mbed_error_msn(mbedtls_error, "mbedtls_pk_rsa");
ERR_FAIL_V_EDMSG(ret, String("Invalid RSA Context: -0x") + String::num_int64(-mbedtls_error, 16) + _err);
}
mbedtls_rsa_free(rsa);
//==========================================================================================
} else {
WARN_PRINT("Unsupported key type");
}
// Frees up resources.
mbedtls_pk_free(&pk);
mbedtls_entropy_free(&entropy);
mbedtls_ctr_drbg_free(&ctr_drbg);
return ret;
}
PackedByteArray Cripter::pk_sign(const String private_key_path, const PackedByteArray data, const String password){
int mbedtls_erro;
const char *pers = "pk_sign";
PackedByteArray hash;
PackedByteArray signature;
const String key_path = ensure_global_path(private_key_path);
hash.resize(HASH_SIZE_SHA_256);
signature.resize(MBEDTLS_PK_SIGNATURE_MAX_SIZE);
mbedtls_pk_context pk_key;
mbedtls_md_context_t md_ctx;
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_pk_init(&pk_key);
mbedtls_md_init(&md_ctx);
mbedtls_entropy_init(&entropy);
mbedtls_ctr_drbg_init(&ctr_drbg);
mbedtls_erro = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, (const unsigned char *)pers, strlen(pers)) ;
if (mbedtls_erro != OK) {
mbedtls_pk_free(&pk_key);
mbedtls_md_free(&md_ctx);
mbedtls_entropy_free(&entropy);
mbedtls_ctr_drbg_free(&ctr_drbg);
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_ctr_drbg_seed");
ERR_FAIL_V_EDMSG(signature, String("Failed to seed the random generator: -0x") + String::num_int64(-mbedtls_erro, 16) + _err);
}
if (password.is_empty()){
mbedtls_erro = mbedtls_pk_parse_keyfile( &pk_key, key_path.utf8().get_data(), nullptr, mbedtls_ctr_drbg_random, &ctr_drbg);
}else{
mbedtls_erro = mbedtls_pk_parse_keyfile(&pk_key, key_path.utf8().get_data(), password.utf8().get_data(), mbedtls_ctr_drbg_random, &ctr_drbg);
}
if (mbedtls_erro != OK) {
mbedtls_pk_free(&pk_key);
mbedtls_md_free(&md_ctx);
mbedtls_entropy_free(&entropy);
mbedtls_ctr_drbg_free(&ctr_drbg);
String _err = mbed_error_msn(mbedtls_erro, "mbedtls_pk_parse_keyfile");
ERR_FAIL_V_EDMSG(signature, String("Failed to parse key file.: -0x") + String::num_int64(-mbedtls_erro, 16) + _err);