-
Notifications
You must be signed in to change notification settings - Fork 0
/
v02enc
executable file
·1556 lines (1325 loc) · 50.9 KB
/
v02enc
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
#!/usr/bin/env php
<?php
/*
Copyright (c) 2023-2024, Yahe
Copyright (c) 2016-2023, SysEleven GmbH
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the SysEleven GmbH nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL SYSELEVEN GMBH BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
##### DEFINITIONS #####
# define armor fields
define("ARMOR_FOOTER", "-----END V02ENC MESSAGE-----");
define("ARMOR_HEADER", "-----BEGIN V02ENC MESSAGE-----");
# define KDF iterations
define("KDF_ITERATIONS", 512000);
# define lengths
define("AES256_BLOCK_SIZE", 16);
define("AES256_KEY_SIZE", 32);
define("ARMOR_RAW_LENGTH", 48);
define("SHA256_OUTPUT_SIZE", 32);
define("STREAM_RAW_LENGTH", ARMOR_RAW_LENGTH*200); // = ~8k blocks
# define encryption fields
define("CHECKMAC", "checkmac");
define("ENCKEY", "enckey");
define("HEADER", "header");
define("HEADERMAC", "headermac");
define("HEADERMACKEY", "headermackey");
define("HEADERNONCE", "headernonce");
define("HEADERSALT", "headersalt");
define("KEY", "key");
define("MESSAGE", "message");
define("MESSAGEMAC", "messagemac");
define("MESSAGEMACKEY", "messagemackey");
define("MESSAGENONCE", "messagenonce");
define("SUBKEY", "subkey");
define("SUBKEYCOUNT", "subkeycount");
define("SUBKEYHEADER", "subkeyheader");
define("SUBKEYLIST", "subkeylist");
define("VERSION", "version");
# define stream fields
define("ARMOR", "armor");
define("BUFFER", "buffer");
define("EOF", "eof");
define("NAME", "name");
define("STREAM", "stream");
# define version number
define("VERSION_BYTE", "\x02");
##### GLOBAL VARIABLES #####
$__INPUTS = [];
$__OUTPUTS = [];
##### INPUT/OUTPUT FUNCTIONS #####
function input_dearmor($name) {
global $__INPUTS;
$result = false;
if (is_string($name)) {
if (array_key_exists($name, $__INPUTS)) {
# read the first byte to check if it contains the version byte
$byte = fread($__INPUTS[$name][STREAM], strlen(VERSION_BYTE));
if (false !== $byte) {
# is the read value the version byte
if (VERSION_BYTE === $byte) {
# put the read byte in the input buffer
$__INPUTS[$name][BUFFER] = $byte;
# this was successful
$result = true;
} else {
$line = "";
# consume empty lines
while (!input_eof($name) && (false !== $line) && (0 === strlen($line))) {
$line = input_readln($name);
# handle the byte that was initially read
if (false !== $line) {
$line = trim($byte.$line, "\n\r");
$byte = "";
}
}
# check if we found the armor header
if (ARMOR_HEADER === $line) {
$__INPUTS[$name][ARMOR] = true;
# this was successful
$result = true;
}
}
}
}
}
return $result;
}
function input_eof($name) {
global $__INPUTS;
$result = false;
if (is_string($name)) {
if (array_key_exists($name, $__INPUTS)) {
# only read the value directly from the file if it isn't set internally
if (!$__INPUTS[$name][EOF]) {
$__INPUTS[$name][EOF] = feof($__INPUTS[$name][STREAM]);
}
$result = $__INPUTS[$name][EOF];
}
}
return $result;
}
function input_finit($name) {
global $__INPUTS;
$result = false;
if (is_string($name)) {
if (array_key_exists($name, $__INPUTS)) {
# clean-up leftovers
$__INPUTS[$name][BUFFER] = "";
unset($__INPUTS[$name]);
$result = true;
}
}
return $result;
}
function input_init($name, $stream) {
global $__INPUTS;
$result = false;
if (is_string($name) && is_resource($stream)) {
if (!array_key_exists($name, $__INPUTS)) {
$__INPUTS[$name] = [ARMOR => false,
BUFFER => "",
EOF => false,
NAME => $name,
STREAM => $stream];
$result = true;
}
}
return $result;
}
function input_isarmor($name) {
global $__INPUTS;
$result = false;
if (is_string($name)) {
if (array_key_exists($name, $__INPUTS)) {
$result = $__INPUTS[$name][ARMOR];
}
}
return $result;
}
function input_read($name, $length) {
global $__INPUTS;
$result = false;
if (is_string($name) && is_int($length)) {
if (array_key_exists($name, $__INPUTS)) {
$result = "";
# clean-up the input buffer first
if (0 < strlen($__INPUTS[$name][BUFFER])) {
$result = substr($__INPUTS[$name][BUFFER], 0, $length);
# remove bytes from the input buffer
$__INPUTS[$name][BUFFER] = substr($__INPUTS[$name][BUFFER], $length);
}
if (strlen($result) < $length) {
$tmp = false;
while (!input_eof($name) && (strlen($result) < $length) && (false !== $result)) {
if (input_isarmor($name)) {
# read next line
$tmp = input_readln($name);
if (false !== $tmp) {
# ignore empty line
if (0 < strlen($tmp)) {
# check if we found the armor footer
if (0 === strcmp($tmp, ARMOR_FOOTER)) {
# set the input to end-of-file
$__INPUTS[$name][EOF] = true;
} else {
# decode the line
$tmp = base64_decode($tmp, true);
if (false !== $tmp) {
# the new block is enough to reach the $length
if (strlen($result)+strlen($tmp) >= $length) {
# how many bytes to take from the new block
$count = $length-strlen($result);
# write bytes to result
$result .= substr($tmp, 0, $count);
# update the input buffer
$__INPUTS[$name][BUFFER] = substr($tmp, $count);
} else {
$result .= $tmp;
}
} else {
# decode errors have priority
$result = false;
}
}
}
} else {
# read errors have priority
$result = false;
}
} else {
# just read the data
$tmp = fread($__INPUTS[$name][STREAM], $length-strlen($result));
if (false !== $tmp) {
$result .= $tmp;
} else {
# read errors have priority
$result = false;
}
}
}
}
}
}
return $result;
}
function input_readln($name) {
global $__INPUTS;
$result = false;
if (is_string($name)) {
if (array_key_exists($name, $__INPUTS)) {
$result = fgets($__INPUTS[$name][STREAM]);
if (false !== $result) {
# remove line breaks from the end of the line
$result = trim($result, "\n\r");
}
}
}
return $result;
}
function input_read_collect($name, $length, &$collection) {
$result = input_read($name, $length);
# if we have returned data, append to $collection
if (is_string($result)) {
$collection .= $result;
}
return $result;
}
function input_trailing($name) {
global $__INPUTS;
$result = false;
if (is_string($name)) {
if (array_key_exists($name, $__INPUTS)) {
# check if we reached eof
$result = !feof($__INPUTS[$name][STREAM]);
# only continue if we have an armored file
if ($result && input_isarmor($name)) {
$line = "";
# consume empty lines
while (!feof($__INPUTS[$name][STREAM]) && (false !== $line) && (0 === strlen($line))) {
$line = input_readln($name);
}
# check if we reached eof or encountered additional content
$result = (!feof($__INPUTS[$name][STREAM]) || (0 < strlen($line)));
}
}
}
return $result;
}
function output_armor($name) {
global $__OUTPUTS;
$result = false;
if (is_string($name)) {
if (array_key_exists($name, $__OUTPUTS)) {
$__OUTPUTS[$name][ARMOR] = true;
# write armor header
$result = (strlen(ARMOR_HEADER)+1 === fwrite($__OUTPUTS[$name][STREAM], ARMOR_HEADER."\n"));
}
}
return $result;
}
function output_finit($name) {
global $__OUTPUTS;
$result = false;
if (is_string($name)) {
if (array_key_exists($name, $__OUTPUTS)) {
$result = true;
if ($__OUTPUTS[$name][ARMOR]) {
# write rest of the output buffer
$tmp = base64_encode($__OUTPUTS[$name][BUFFER]);
$result &= (strlen($tmp) === fwrite($__OUTPUTS[$name][STREAM], $tmp));
# write armor footer
$result &= (strlen(ARMOR_FOOTER)+1 === fwrite($__OUTPUTS[$name][STREAM], "\n".ARMOR_FOOTER));
# clean-up leftovers
$__OUTPUTS[$name][BUFFER] = "";
}
if ($result) {
unset($__OUTPUTS[$name]);
}
}
}
return $result;
}
function output_init($name, $stream) {
global $__OUTPUTS;
$result = false;
if (is_string($name) && is_resource($stream)) {
if (!array_key_exists($name, $__OUTPUTS)) {
$__OUTPUTS[$name] = [ARMOR => false,
BUFFER => "",
NAME => $name,
STREAM => $stream];
$result = true;
}
}
return $result;
}
function output_write($name, $data) {
global $__OUTPUTS;
$result = false;
if (is_string($name) && is_string($data)) {
if (array_key_exists($name, $__OUTPUTS)) {
if ($__OUTPUTS[$name][ARMOR]) {
# prepare result
$result = true;
# prepend the current output buffer to the data
$data = $__OUTPUTS[$name][BUFFER].$data;
# prepare Base64 encoding
$position = 0;
# split data into chunks to Base64-encode and write them
while (strlen($data)-$position >= ARMOR_RAW_LENGTH) {
$tmp = base64_encode(substr($data, $position, ARMOR_RAW_LENGTH));
$result &= (strlen($tmp)+1 === fwrite($__OUTPUTS[$name][STREAM], "{$tmp}\n"));
# increase the position
if ($result) {
$position = $position+ARMOR_RAW_LENGTH;
} else {
# exit the loop
break;
}
}
# proceed if nothing went wrong
if ($result) {
# put rest of the data in write buffer
$__OUTPUTS[$name][BUFFER] = substr($data, $position);
} else {
# clean-up leftovers
$__OUTPUTS[$name][BUFFER] = "";
}
} else {
# just write the data
$result = (strlen($data) === fwrite($__OUTPUTS[$name][STREAM], $data));
}
}
}
return $result;
}
##### CRYPTOGRAPHIC FUNCTIONS #####
# TODO: chr() and ord() are not time-constant
function increment($counter, $increment = 0x01) {
$result = $counter;
if (is_string($result) && is_int($increment) && (0x00 <= $increment)) {
# add increment to the result
for ($index = strlen($result)-0x01; $index >= 0x00; $index--) {
$tmp = ((ord($result[$index]) + $increment) >> 0x08);
$result[$index] = chr((ord($result[$index]) + $increment) & 0xFF);
$increment = $tmp;
}
}
return $result;
}
# reusable header decryption
function decrypt_header($input, $recipients, &$data, &$error) {
$result = false;
$error = false;
if (is_string($input) && is_array($recipients) && is_array($data)) {
if (0 < count($recipients)) {
# prepare MAC comparison
$data[HEADER] = "";
$data[VERSION] = input_read_collect($input, 1, $data[HEADER]);
$data[HEADERSALT] = input_read_collect($input, AES256_KEY_SIZE, $data[HEADER]);
$data[HEADERNONCE] = input_read_collect($input, AES256_BLOCK_SIZE, $data[HEADER]);
$data[MESSAGENONCE] = input_read_collect($input, AES256_BLOCK_SIZE, $data[HEADER]);
$data[SUBKEYCOUNT] = hexdec(bin2hex(input_read_collect($input, 2, $data[HEADER])));
$data[SUBKEYLIST] = [];
# iterate through the subkeys
for ($i = 0; $i < $data[SUBKEYCOUNT]; $i++) {
$data[SUBKEYLIST][$i] = [];
$data[SUBKEYLIST][$i][CHECKMAC] = [];
$data[SUBKEYLIST][$i][ENCKEY] = [];
$data[SUBKEYLIST][$i][KEY] = [];
$data[SUBKEYLIST][$i][HEADERMACKEY] = [];
$data[SUBKEYLIST][$i][SUBKEY] = [];
$data[SUBKEYLIST][$i][SUBKEYHEADER] = input_read_collect($input, AES256_KEY_SIZE, $data[HEADER]);
}
# do not add the header mac to the overall header
$data[HEADERMAC] = input_read($input, SHA256_OUTPUT_SIZE);
if (VERSION_BYTE === $data[VERSION]) {
# prevent excessive key search if we reached eof,
# this is definitely a malformed input
if (!input_eof($input)) {
# set default key value
$data[KEY] = false;
# iterate through the recipients and see whether we find a fitting key
$keys = array_keys($recipients);
$subkeys = array_keys($data[SUBKEYLIST]);
foreach ($subkeys as $subkey) {
foreach ($keys as $key) {
# derive secure key from recipient key and salt
$data[SUBKEYLIST][$subkey][SUBKEY][$key] = hash_pbkdf2("sha256", $recipients[$key], $data[HEADERSALT], KDF_ITERATIONS, 0, true);
if (false !== $data[SUBKEYLIST][$subkey][SUBKEY][$key]) {
# decrypt subkey with derived secure key
$data[SUBKEYLIST][$subkey][KEY][$key] = openssl_decrypt($data[SUBKEYLIST][$subkey][SUBKEYHEADER], "aes-256-ctr", $data[SUBKEYLIST][$subkey][SUBKEY][$key], OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $data[HEADERNONCE]);
if (false !== $data[SUBKEYLIST][$subkey][KEY][$key]) {
# generate mac keys
$data[SUBKEYLIST][$subkey][HEADERMACKEY][$key] = hash_hmac("sha256", "mac-header", $data[SUBKEYLIST][$subkey][KEY][$key], true);
if (false !== $data[SUBKEYLIST][$subkey][HEADERMACKEY][$key]) {
# calculate header mac with header mac key
$data[SUBKEYLIST][$subkey][CHECKMAC][$key] = hash_hmac("sha256", $data[HEADER], $data[SUBKEYLIST][$subkey][HEADERMACKEY][$key], true);
if (false !== $data[SUBKEYLIST][$subkey][CHECKMAC][$key]) {
if (hash_equals($data[SUBKEYLIST][$subkey][CHECKMAC][$key], $data[HEADERMAC])) {
# generate encryption key
$data[KEY] = $data[SUBKEYLIST][$subkey][KEY][$key];
}
}
}
}
}
}
}
if (false !== $data[KEY]) {
$data[ENCKEY] = hash_hmac("sha256", "enc", $data[KEY], true); // generate enc key
$data[HEADERMACKEY] = hash_hmac("sha256", "mac-header" , $data[KEY], true); // generate mac key
$data[MESSAGEMACKEY] = hash_hmac("sha256", "mac-message", $data[KEY], true); // generate mac key
if ((false !== $data[ENCKEY]) && (false !== $data[MESSAGEMACKEY]) && (false !== $data[MESSAGEMACKEY])) {
$result = true;
} else {
$error = "Key expansion failed.";
}
} else {
$error = "No matching recipient provided.";
}
} else {
$error = "Message has malformed header.";
}
} else {
$error = "Message has wrong version.";
}
} else {
$error = "No recipients provided.";
}
} else {
$error = "Insufficient arguments provided.";
}
return $result;
}
# reusable message decryption
function decrypt_message($input, $output, &$data, &$error) {
$result = false;
$error = false;
if (is_string($input) && is_string($output) && is_array($data)) {
# prepare message hmac
if ($checkmac = hash_init("sha256", HASH_HMAC, $data[MESSAGEMACKEY])) {
hash_update($checkmac, $data[HEADER]);
hash_update($checkmac, $data[HEADERMAC]);
# prepare streamed message encryption
$buffer = "";
$counter = $data[MESSAGENONCE];
while (!input_eof($input) && (false === $error)) {
# we read a specific number of ARMOR_RAW_LENGTH blocks to
# optimize the input and output buffering behaviour by
# ensuring that the block size aligns with the AES block
# size, armor raw length and armor Base64 length
$tmp = input_read($input, STREAM_RAW_LENGTH);
if (false !== $tmp) {
# add read string to buffer
$buffer .= $tmp;
# get number of AES blocks,
# keep 32 bytes at the end for a potential message mac
$blocks = 0;
if (SHA256_OUTPUT_SIZE < strlen($buffer)) {
$blocks = intdiv(strlen($buffer)-SHA256_OUTPUT_SIZE, AES256_BLOCK_SIZE);
}
if (0 < $blocks) {
# decrypt full block lengths
$tmp = openssl_decrypt(substr($buffer, 0, $blocks*AES256_BLOCK_SIZE), "aes-256-ctr", $data[ENCKEY], OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $counter);
if (false !== $tmp) {
hash_update($checkmac, substr($buffer, 0, $blocks*AES256_BLOCK_SIZE));
# increment the counter for the next round
$counter = increment($counter, $blocks);
if (output_write($output, $tmp)) {
$buffer = substr($buffer, $blocks*AES256_BLOCK_SIZE);
} else {
$error = "Message could not be written to output.";
}
} else {
$error = "Message decryption failed.";
}
}
} else {
$error = "Message could not be read from input.";
}
}
# handle the rest of the buffer
if (false === $error) {
# get the message mac
$data[MESSAGEMAC] = substr($buffer, -SHA256_OUTPUT_SIZE);
# prepare the buffer for the last round
$buffer = substr($buffer, 0, -SHA256_OUTPUT_SIZE);
# decrypt what's left
$tmp = openssl_decrypt($buffer, "aes-256-ctr", $data[ENCKEY], OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $counter);
if (false !== $tmp) {
hash_update($checkmac, $buffer);
if (!output_write($output, $tmp)) {
$error = "Message could not be written to output.";
}
} else {
$error = "Message decryption failed.";
}
}
if (false === $error) {
# calculate message mac with message mac key
$data[CHECKMAC] = hash_final($checkmac, true);
$result = hash_equals($data[CHECKMAC], $data[MESSAGEMAC]);
if (!$result) {
$error = "Message MAC does not belong to message.";
}
} else {
# keep the error message of the loop
}
} else {
$error = "Message HMAC could not be initialized.";
}
} else {
$error = "Insufficient arguments provided.";
}
return $result;
}
# reusable message encryption
function encrypt_message($input, $output, &$data, &$error) {
$result = false;
$error = false;
if (is_string($input) && is_string($output) && is_array($data)) {
# concatenate the header
$data[HEADER] = $data[VERSION];
$data[HEADER] .= $data[HEADERSALT];
$data[HEADER] .= $data[HEADERNONCE];
$data[HEADER] .= $data[MESSAGENONCE];
$data[HEADER] .= hex2bin(sprintf("%04x", $data[SUBKEYCOUNT]));
$keys = array_keys($data[SUBKEYHEADER]);
foreach ($keys as $key) {
$data[HEADER] .= $data[SUBKEYHEADER][$key];
}
# calculate the header mac with the header mac key
$data[HEADERMAC] = hash_hmac("sha256", $data[HEADER], $data[HEADERMACKEY], true);
if (false !== $data[HEADERMAC]) {
# write header to output
if (output_write($output, $data[HEADER].$data[HEADERMAC])) {
# prepare message hmac
if ($messagemac = hash_init("sha256", HASH_HMAC, $data[MESSAGEMACKEY])) {
hash_update($messagemac, $data[HEADER]);
hash_update($messagemac, $data[HEADERMAC]);
# prepare streamed message encryption
$buffer = "";
$counter = $data[MESSAGENONCE];
while (!input_eof($input) && (false === $error)) {
# we read a specific number of ARMOR_RAW_LENGTH blocks to
# optimize the input and output buffering behaviour by
# ensuring that the block size aligns with the AES block
# size, armor raw length and armor Base64 length
$tmp = input_read($input, STREAM_RAW_LENGTH);
if (false !== $tmp) {
# add read string to buffer
$buffer .= $tmp;
# get number of AES blocks
$blocks = intdiv(strlen($buffer), AES256_BLOCK_SIZE);
if (0 < $blocks) {
# encrypt full block lengths
$tmp = openssl_encrypt(substr($buffer, 0, $blocks*AES256_BLOCK_SIZE), "aes-256-ctr", $data[ENCKEY], OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $counter);
if (false !== $tmp) {
hash_update($messagemac, $tmp);
# increment the counter for the next round
$counter = increment($counter, $blocks);
if (output_write($output, $tmp)) {
$buffer = substr($buffer, $blocks*AES256_BLOCK_SIZE);
} else {
$error = "Message could not be written to output.";
}
} else {
$error = "Message encryption failed.";
}
}
} else {
$error = "Message could not be read from input.";
}
}
# handle the rest of the buffer
if (false === $error) {
# encrypt what's left
$tmp = openssl_encrypt($buffer, "aes-256-ctr", $data[ENCKEY], OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $counter);
if (false !== $tmp) {
hash_update($messagemac, $tmp);
if (output_write($output, $tmp)) {
# calculate message mac with message mac key
$data[MESSAGEMAC] = hash_final($messagemac, true);
$result = output_write($output, $data[MESSAGEMAC]);
if (!$result) {
$error = "Message could not be written to output.";
}
} else {
$error = "Message could not be written to output.";
}
} else {
$error = "Message encryption failed.";
}
}
} else {
$error = "Message HMAC could not be initialized.";
}
} else {
$error = "Header could not be written to output.";
}
} else {
$error = "Header MAC calculation failed.";
}
} else {
$error = "Insufficient arguments provided.";
}
return $result;
}
function decrypt_v02($input, $output, $recipients, &$error) {
$result = false;
$error = false;
if (is_string($input) && is_string($output)) {
$data = [];
try {
if (decrypt_header($input, $recipients, $data, $error)) {
$result = decrypt_message($input, $output, $data, $error);
if (!$result) {
# keep the error text from decrypt_message()
}
} else {
# keep the error text from decrypt_header()
}
} finally {
zeroize_array($data);
}
} else {
$error = "Insufficient arguments provided.";
}
return $result;
}
function encrypt_v02($input, $output, $recipients, &$error) {
$result = false;
$error = false;
if (is_string($input) && is_string($output) && is_array($recipients)) {
if (0xFFFF >= count($recipients)) {
if (0 < count($recipients)) {
$data = [];
try {
# set and generate values
$data[VERSION] = "\x02";
$data[HEADERSALT] = openssl_random_pseudo_bytes(AES256_KEY_SIZE, $strong_crypto_headersalt); // generate random salt
$data[KEY] = openssl_random_pseudo_bytes(AES256_KEY_SIZE, $strong_crypto_key); // generate random key
if ((false !== $data[HEADERSALT]) && (false !== $data[KEY]) && $strong_crypto_headersalt && $strong_crypto_key) {
$data[ENCKEY] = hash_hmac("sha256", "enc", $data[KEY], true); // generate enc key
$data[HEADERMACKEY] = hash_hmac("sha256", "mac-header", $data[KEY], true); // generate mac key
$data[MESSAGEMACKEY] = hash_hmac("sha256", "mac-message", $data[KEY], true); // generate mac key
if ((false !== $data[ENCKEY]) && (false !== $data[HEADERMACKEY]) && (false !== $data[MESSAGEMACKEY])) {
# use the same time for both nonces
$time = time();
$data[HEADERNONCE] = hex2bin(sprintf("%016xFFFFFFFF00000000", $time)); // generate nonce
$data[MESSAGENONCE] = hex2bin(sprintf("%016x0000000000000000", $time)); // generate nonce
if ((false !== $data[HEADERNONCE]) && (false !== $data[MESSAGENONCE])) {
# iterate through recipients and generate rsa keys
$data[SUBKEY] = [];
$data[SUBKEYCOUNT] = 0;
$data[SUBKEYHEADER] = [];
$keys = array_keys($recipients);
foreach ($keys as $key) {
$data[SUBKEY][$key] = hash_pbkdf2("sha256", $recipients[$key], $data[HEADERSALT], KDF_ITERATIONS, 0, true);
if (false !== $data[SUBKEY][$key]) {
$data[SUBKEYHEADER][$key] = openssl_encrypt($data[KEY], "aes-256-ctr", $data[SUBKEY][$key], OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $data[HEADERNONCE]);
if (false !== $data[SUBKEYHEADER][$key]) {
$data[SUBKEYCOUNT] = $data[SUBKEYCOUNT]+1;
}
}
}
# check if we were able to encrypt for all recipients
if (count($recipients) === $data[SUBKEYCOUNT]) {
$result = encrypt_message($input, $output, $data, $error);
if (!$result) {
# keep the error text from encrypt_message()
}
} else {
$error = "Key encryption failed.";
}
} else {
$error = "Nonce generation failed.";
}
} else {
$error = "Key expansion failed.";
}
} else {
$error = "Randomness generation failed.";
}
} finally {
zeroize_array($data);
}
} else {
$error = "No recipients provided.";
}
} else {
$error = "Too many recipients provided.";
}
} else {
$error = "Insufficient arguments provided.";
}
return $result;
}
function update_v02($input, $update, $output, $recipients, &$error) {
$result = false;
$error = false;
if (is_string($input) && is_string($update) && is_string($output)) {
$data = [];
try {
if (decrypt_header($input, $recipients, $data, $error)) {
$newdata = [];
try {
# copy values from $data to $newdata to separate decryption from re-encryption
$newdata[ENCKEY] = $data[ENCKEY];
$newdata[HEADERMACKEY] = $data[HEADERMACKEY];
$newdata[HEADERNONCE] = $data[HEADERNONCE];
$newdata[HEADERSALT] = $data[HEADERSALT];
$newdata[KEY] = $data[KEY];
$newdata[MESSAGEMACKEY] = $data[MESSAGEMACKEY];
$newdata[SUBKEYCOUNT] = $data[SUBKEYCOUNT];
$newdata[SUBKEYHEADER] = [];
$newdata[VERSION] = $data[VERSION];
# copy the subkey headers from $data to $newdata to separate decryption from re-encryption
$keys = array_keys($data[SUBKEYLIST]);
foreach ($keys as $key) {
$newdata[SUBKEYHEADER][$key] = $data[SUBKEYLIST][$key][SUBKEYHEADER];
}
# !!! create a NEW message nonce to prevent nonce reuse
$newdata[MESSAGENONCE] = hex2bin(sprintf("%016x0000000000000000", time())); // generate nonce
if (false !== $newdata[MESSAGENONCE]) {
$result = encrypt_message($update, $output, $newdata, $error);
if (!$result) {
# keep the error text from encrypt_message()
}
} else {
$error = "Nonce generation failed.";
}
} finally {
zeroize_array($newdata);
}
} else {
# keep the error text from decrypt_header()
}
} finally {
zeroize_array($data);
}
} else {
$error = "Insufficient arguments provided.";
}
return $result;
}
function zeroize_array(&$array) {
$result = false;
if (is_array($array)) {
$result = true;
$keys = array_keys($array);
foreach ($keys as $key) {
if (is_array($array[$key])) {
$result = $result && zeroize_array($array[$key]);
} elseif (is_string($array[$key])) {
for ($i = 0; $i < strlen($array[$key]); $i++) {
$array[$key][$i] = "\0";
}
}
}
}
return $result;
}
##### HELPER FUNCTIONS #####
function check_armor($options, $rest, &$error) {
return (0 < count(get_opt_values($options, "a", "armor")));
}
function check_decrypt($options, $rest, &$error) {
return (0 < count(get_opt_values($options, "d", "decrypt")));
}
function check_encrypt($options, $rest, &$error) {
return (0 < count(get_opt_values($options, "e", "encrypt")));
}
function check_file($options, $rest, &$error) {
$result = false;
if (1 === count($rest)) {
if ("-" === $rest[0]) {
$result = "php://stdin";
} elseif (is_file($rest[0])) {
$result = $rest[0];
} else {
if (!is_array($error)) {
$error = [];
}
$error[] = "File does not exist: {$rest[0]}";
}
} elseif (1 < count($rest)) {
if (!is_array($error)) {
$error = [];
}
$error[] = "Too many files provided.";
}
return $result;
}
function check_help($options, $rest, &$error) {
return (0 < count(get_opt_values($options, "h", "help")));
}
function check_key($options, $rest, &$error) {
$result = false;
$key = get_opt_values($options, "k", "key");
if (0 < count($key)) {