/
SymmetricKey.php
2955 lines (2705 loc) · 111 KB
/
SymmetricKey.php
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
<?php
/**
* Base Class for all \phpseclib3\Crypt\* cipher classes
*
* PHP version 5
*
* Internally for phpseclib developers:
* If you plan to add a new cipher class, please note following rules:
*
* - The new \phpseclib3\Crypt\* cipher class should extend \phpseclib3\Crypt\Common\SymmetricKey
*
* - Following methods are then required to be overridden/overloaded:
*
* - encryptBlock()
*
* - decryptBlock()
*
* - setupKey()
*
* - All other methods are optional to be overridden/overloaded
*
* - Look at the source code of the current ciphers how they extend \phpseclib3\Crypt\Common\SymmetricKey
* and take one of them as a start up for the new cipher class.
*
* - Please read all the other comments/notes/hints here also for each class var/method
*
* @author Jim Wigginton <terrafrost@php.net>
* @author Hans-Juergen Petrich <petrich@tronic-media.com>
* @copyright 2007 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net
*/
declare(strict_types=1);
namespace phpseclib3\Crypt\Common;
use phpseclib3\Common\Functions\Strings;
use phpseclib3\Crypt\Blowfish;
use phpseclib3\Crypt\Hash;
use phpseclib3\Exception\BadDecryptionException;
use phpseclib3\Exception\BadMethodCallException;
use phpseclib3\Exception\BadModeException;
use phpseclib3\Exception\InconsistentSetupException;
use phpseclib3\Exception\InsufficientSetupException;
use phpseclib3\Exception\LengthException;
use phpseclib3\Exception\LogicException;
use phpseclib3\Exception\RuntimeException;
use phpseclib3\Exception\UnsupportedAlgorithmException;
use phpseclib3\Math\BigInteger;
use phpseclib3\Math\BinaryField;
use phpseclib3\Math\PrimeField;
/**
* Base Class for all \phpseclib3\Crypt\* cipher classes
*
* @author Jim Wigginton <terrafrost@php.net>
* @author Hans-Juergen Petrich <petrich@tronic-media.com>
*/
abstract class SymmetricKey
{
/**
* Encrypt / decrypt using the Counter mode.
*
* Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
* @see \phpseclib3\Crypt\Common\SymmetricKey::encrypt()
* @see \phpseclib3\Crypt\Common\SymmetricKey::decrypt()
*/
public const MODE_CTR = -1;
/**
* Encrypt / decrypt using the Electronic Code Book mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
* @see \phpseclib3\Crypt\Common\SymmetricKey::encrypt()
* @see \phpseclib3\Crypt\Common\SymmetricKey::decrypt()
*/
public const MODE_ECB = 1;
/**
* Encrypt / decrypt using the Code Book Chaining mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
* @see \phpseclib3\Crypt\Common\SymmetricKey::encrypt()
* @see \phpseclib3\Crypt\Common\SymmetricKey::decrypt()
*/
public const MODE_CBC = 2;
/**
* Encrypt / decrypt using the Cipher Feedback mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
* @see \phpseclib3\Crypt\Common\SymmetricKey::encrypt()
* @see \phpseclib3\Crypt\Common\SymmetricKey::decrypt()
*/
public const MODE_CFB = 3;
/**
* Encrypt / decrypt using the Cipher Feedback mode (8bit)
*
* @see \phpseclib3\Crypt\Common\SymmetricKey::encrypt()
* @see \phpseclib3\Crypt\Common\SymmetricKey::decrypt()
*/
public const MODE_CFB8 = 7;
/**
* Encrypt / decrypt using the Output Feedback mode (8bit)
*
* @see \phpseclib3\Crypt\Common\SymmetricKey::encrypt()
* @see \phpseclib3\Crypt\Common\SymmetricKey::decrypt()
*/
public const MODE_OFB8 = 8;
/**
* Encrypt / decrypt using the Output Feedback mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
* @see \phpseclib3\Crypt\Common\SymmetricKey::encrypt()
* @see \phpseclib3\Crypt\Common\SymmetricKey::decrypt()
*/
public const MODE_OFB = 4;
/**
* Encrypt / decrypt using Galois/Counter mode.
*
* @link https://en.wikipedia.org/wiki/Galois/Counter_Mode
* @see \phpseclib3\Crypt\Common\SymmetricKey::encrypt()
* @see \phpseclib3\Crypt\Common\SymmetricKey::decrypt()
*/
public const MODE_GCM = 5;
/**
* Encrypt / decrypt using streaming mode.
*
* @see \phpseclib3\Crypt\Common\SymmetricKey::encrypt()
* @see \phpseclib3\Crypt\Common\SymmetricKey::decrypt()
*/
public const MODE_STREAM = 6;
/**
* Mode Map
*
* @see \phpseclib3\Crypt\Common\SymmetricKey::__construct()
*/
public const MODE_MAP = [
'ctr' => self::MODE_CTR,
'ecb' => self::MODE_ECB,
'cbc' => self::MODE_CBC,
'cfb' => self::MODE_CFB,
'cfb8' => self::MODE_CFB8,
'ofb' => self::MODE_OFB,
'ofb8' => self::MODE_OFB8,
'gcm' => self::MODE_GCM,
'stream' => self::MODE_STREAM,
];
/**
* Base value for the internal implementation $engine switch
*
* @see \phpseclib3\Crypt\Common\SymmetricKey::__construct()
*/
public const ENGINE_INTERNAL = 1;
/**
* Base value for the eval() implementation $engine switch
*
* @see \phpseclib3\Crypt\Common\SymmetricKey::__construct()
*/
public const ENGINE_EVAL = 2;
/**
* Base value for the openssl implementation $engine switch
*
* @see \phpseclib3\Crypt\Common\SymmetricKey::__construct()
*/
public const ENGINE_OPENSSL = 4;
/**
* Base value for the libsodium implementation $engine switch
*
* @see \phpseclib3\Crypt\Common\SymmetricKey::__construct()
*/
public const ENGINE_LIBSODIUM = 5;
/**
* Base value for the openssl / gcm implementation $engine switch
*
* @see \phpseclib3\Crypt\Common\SymmetricKey::__construct()
*/
public const ENGINE_OPENSSL_GCM = 6;
/**
* Engine Reverse Map
*
* @see \phpseclib3\Crypt\Common\SymmetricKey::getEngine()
*/
public const ENGINE_MAP = [
self::ENGINE_INTERNAL => 'PHP',
self::ENGINE_EVAL => 'Eval',
self::ENGINE_OPENSSL => 'OpenSSL',
self::ENGINE_LIBSODIUM => 'libsodium',
self::ENGINE_OPENSSL_GCM => 'OpenSSL (GCM)',
];
/**
* The Encryption Mode
*
* @see self::__construct()
* @var int
*/
protected $mode;
/**
* The Block Length of the block cipher
*
* @var int
*/
protected $block_size = 16;
/**
* The Key
*
* @see self::setKey()
* @var string
*/
protected $key = false;
/**
* HMAC Key
*
* @see self::setupGCM()
* @var null|string
*/
private $hKey = null;
/**
* The Initialization Vector
*
* @see self::setIV()
* @var string
*/
protected $iv = false;
/**
* A "sliding" Initialization Vector
*
* @see self::enableContinuousBuffer()
* @see self::clearBuffers()
* @var string
*/
protected $encryptIV;
/**
* A "sliding" Initialization Vector
*
* @see self::enableContinuousBuffer()
* @see self::clearBuffers()
* @var string
*/
protected $decryptIV;
/**
* Continuous Buffer status
*
* @see self::enableContinuousBuffer()
* @var bool
*/
protected $continuousBuffer = false;
/**
* Encryption buffer for CTR, OFB and CFB modes
*
* @see self::encrypt()
* @see self::clearBuffers()
* @var array
*/
protected $enbuffer;
/**
* Decryption buffer for CTR, OFB and CFB modes
*
* @see self::decrypt()
* @see self::clearBuffers()
* @var array
*/
protected $debuffer;
/**
* Does internal cipher state need to be (re)initialized?
*
* @see self::setKey()
* @see self::setIV()
* @see self::disableContinuousBuffer()
* @var bool
*/
protected $changed = true;
/**
* Does Eval engie need to be (re)initialized?
*
* @see self::setup()
* @var bool
*/
protected $nonIVChanged = true;
/**
* Padding status
*
* @see self::enablePadding()
* @var bool
*/
private $padding = true;
/**
* Is the mode one that is paddable?
*
* @see self::__construct()
* @var bool
*/
private $paddable = false;
/**
* Holds which crypt engine internaly should be use,
* which will be determined automatically on __construct()
*
* Currently available $engines are:
* - self::ENGINE_LIBSODIUM (very fast, php-extension: libsodium, extension_loaded('libsodium') required)
* - self::ENGINE_OPENSSL_GCM (very fast, php-extension: openssl, extension_loaded('openssl') required)
* - self::ENGINE_OPENSSL (very fast, php-extension: openssl, extension_loaded('openssl') required)
* - self::ENGINE_EVAL (medium, pure php-engine, no php-extension required)
* - self::ENGINE_INTERNAL (slower, pure php-engine, no php-extension required)
*
* @see self::setEngine()
* @see self::encrypt()
* @see self::decrypt()
* @var int
*/
protected $engine;
/**
* Holds the preferred crypt engine
*
* @see self::setEngine()
* @see self::setPreferredEngine()
* @var int
*/
private $preferredEngine;
/**
* The openssl specific name of the cipher
*
* Only used if $engine == self::ENGINE_OPENSSL
*
* @link http://www.php.net/openssl-get-cipher-methods
* @var string
*/
protected $cipher_name_openssl;
/**
* The openssl specific name of the cipher in ECB mode
*
* If OpenSSL does not support the mode we're trying to use (CTR)
* it can still be emulated with ECB mode.
*
* @link http://www.php.net/openssl-get-cipher-methods
* @var string
*/
protected $cipher_name_openssl_ecb;
/**
* The default salt used by setPassword()
*
* @see self::setPassword()
* @var string
*/
private $password_default_salt = 'phpseclib/salt';
/**
* The name of the performance-optimized callback function
*
* Used by encrypt() / decrypt()
* only if $engine == self::ENGINE_INTERNAL
*
* @see self::encrypt()
* @see self::decrypt()
* @see self::setupInlineCrypt()
* @var Callback
*/
protected $inline_crypt;
/**
* If OpenSSL can be used in ECB but not in CTR we can emulate CTR
*
* @see self::openssl_ctr_process()
* @var bool
*/
private $openssl_emulate_ctr = false;
/**
* Has the key length explicitly been set or should it be derived from the key, itself?
*
* @see self::setKeyLength()
* @var bool
*/
protected $explicit_key_length = false;
/**
* Hash subkey for GHASH
*
* @see self::setupGCM()
* @see self::ghash()
* @var BinaryField\Integer
*/
private $h;
/**
* Additional authenticated data
*
* @var string
*/
protected $aad = '';
/**
* Authentication Tag produced after a round of encryption
*
* @var string
*/
protected $newtag = false;
/**
* Authentication Tag to be verified during decryption
*
* @var string
*/
protected $oldtag = false;
/**
* GCM Binary Field
*
* @see self::__construct()
* @see self::ghash()
* @var BinaryField
*/
private static $gcmField;
/**
* Poly1305 Prime Field
*
* @see self::enablePoly1305()
* @see self::poly1305()
* @var PrimeField
*/
private static $poly1305Field;
/**
* Poly1305 Key
*
* @see self::setPoly1305Key()
* @see self::poly1305()
* @var string
*/
protected $poly1305Key;
/**
* Poly1305 Flag
*
* @see self::setPoly1305Key()
* @see self::enablePoly1305()
* @var boolean
*/
protected $usePoly1305 = false;
/**
* The Original Initialization Vector
*
* GCM uses the nonce to build the IV but we want to be able to distinguish between nonce-derived
* IV's and user-set IV's
*
* @see self::setIV()
* @var string
*/
private $origIV = false;
/**
* Nonce
*
* Only used with GCM. We could re-use setIV() but nonce's can be of a different length and
* toggling between GCM and other modes could be more complicated if we re-used setIV()
*
* @see self::setNonce()
* @var string
*/
protected $nonce = false;
/**
* Default Constructor.
*
* $mode could be:
*
* - ecb
*
* - cbc
*
* - ctr
*
* - cfb
*
* - cfb8
*
* - ofb
*
* - ofb8
*
* - gcm
*
* @throws BadModeException if an invalid / unsupported mode is provided
*/
public function __construct(string $mode)
{
$mode = strtolower($mode);
// necessary because of 5.6 compatibility; we can't do isset(self::MODE_MAP[$mode]) in 5.6
$map = self::MODE_MAP;
if (!isset($map[$mode])) {
throw new BadModeException('No valid mode has been specified');
}
$mode = self::MODE_MAP[$mode];
// $mode dependent settings
switch ($mode) {
case self::MODE_ECB:
case self::MODE_CBC:
$this->paddable = true;
break;
case self::MODE_CTR:
case self::MODE_CFB:
case self::MODE_CFB8:
case self::MODE_OFB:
case self::MODE_OFB8:
case self::MODE_STREAM:
$this->paddable = false;
break;
case self::MODE_GCM:
if ($this->block_size != 16) {
throw new BadModeException('GCM is only valid for block ciphers with a block size of 128 bits');
}
if (!isset(self::$gcmField)) {
self::$gcmField = new BinaryField(128, 7, 2, 1, 0);
}
$this->paddable = false;
break;
default:
throw new BadModeException('No valid mode has been specified');
}
$this->mode = $mode;
static::initialize_static_variables();
}
/**
* Initialize static variables
*/
protected static function initialize_static_variables(): void
{
}
/**
* Sets the initialization vector.
*
* setIV() is not required when ecb or gcm modes are being used.
*
* {@internal Can be overwritten by a sub class, but does not have to be}
*
* @throws LengthException if the IV length isn't equal to the block size
* @throws BadMethodCallException if an IV is provided when one shouldn't be
*/
public function setIV(string $iv): void
{
if ($this->mode == self::MODE_ECB) {
throw new BadMethodCallException('This mode does not require an IV.');
}
if ($this->mode == self::MODE_GCM) {
throw new BadMethodCallException('Use setNonce instead');
}
if (!$this->usesIV()) {
throw new BadMethodCallException('This algorithm does not use an IV.');
}
if (strlen($iv) != $this->block_size) {
throw new LengthException('Received initialization vector of size ' . strlen($iv) . ', but size ' . $this->block_size . ' is required');
}
$this->iv = $this->origIV = $iv;
$this->changed = true;
}
/**
* Enables Poly1305 mode.
*
* Once enabled Poly1305 cannot be disabled.
*
* @throws BadMethodCallException if Poly1305 is enabled whilst in GCM mode
*/
public function enablePoly1305(): void
{
if ($this->mode == self::MODE_GCM) {
throw new BadMethodCallException('Poly1305 cannot be used in GCM mode');
}
$this->usePoly1305 = true;
}
/**
* Enables Poly1305 mode.
*
* Once enabled Poly1305 cannot be disabled. If $key is not passed then an attempt to call createPoly1305Key
* will be made.
*
* @param string|null $key optional
* @throws LengthException if the key isn't long enough
* @throws BadMethodCallException if Poly1305 is enabled whilst in GCM mode
*/
public function setPoly1305Key(?string $key = null): void
{
if ($this->mode == self::MODE_GCM) {
throw new BadMethodCallException('Poly1305 cannot be used in GCM mode');
}
if (!is_string($key) || strlen($key) != 32) {
throw new LengthException('The Poly1305 key must be 32 bytes long (256 bits)');
}
if (!isset(self::$poly1305Field)) {
// 2^130-5
self::$poly1305Field = new PrimeField(new BigInteger('3fffffffffffffffffffffffffffffffb', 16));
}
$this->poly1305Key = $key;
$this->usePoly1305 = true;
}
/**
* Sets the nonce.
*
* setNonce() is only required when gcm is used
*
* @throws BadMethodCallException if an nonce is provided when one shouldn't be
*/
public function setNonce(string $nonce): void
{
if ($this->mode != self::MODE_GCM) {
throw new BadMethodCallException('Nonces are only used in GCM mode.');
}
$this->nonce = $nonce;
$this->setEngine();
}
/**
* Sets additional authenticated data
*
* setAAD() is only used by gcm or in poly1305 mode
*
* @throws BadMethodCallException if mode isn't GCM or if poly1305 isn't being utilized
*/
public function setAAD(string $aad): void
{
if ($this->mode != self::MODE_GCM && !$this->usePoly1305) {
throw new BadMethodCallException('Additional authenticated data is only utilized in GCM mode or with Poly1305');
}
$this->aad = $aad;
}
/**
* Returns whether or not the algorithm uses an IV
*/
public function usesIV(): bool
{
return $this->mode != self::MODE_GCM && $this->mode != self::MODE_ECB;
}
/**
* Returns whether or not the algorithm uses a nonce
*/
public function usesNonce(): bool
{
return $this->mode == self::MODE_GCM;
}
/**
* Returns the current key length in bits
*/
public function getKeyLength(): int
{
return $this->key_length << 3;
}
/**
* Returns the current block length in bits
*/
public function getBlockLength(): int
{
return $this->block_size << 3;
}
/**
* Returns the current block length in bytes
*/
public function getBlockLengthInBytes(): int
{
return $this->block_size;
}
/**
* Sets the key length.
*
* Keys with explicitly set lengths need to be treated accordingly
*/
public function setKeyLength(int $length): void
{
$this->explicit_key_length = $length >> 3;
if (is_string($this->key) && strlen($this->key) != $this->explicit_key_length) {
$this->key = false;
throw new InconsistentSetupException('Key has already been set and is not ' . $this->explicit_key_length . ' bytes long');
}
}
/**
* Sets the key.
*
* The min/max length(s) of the key depends on the cipher which is used.
* If the key not fits the length(s) of the cipher it will paded with null bytes
* up to the closest valid key length. If the key is more than max length,
* we trim the excess bits.
*
* If the key is not explicitly set, it'll be assumed to be all null bytes.
*
* {@internal Could, but not must, extend by the child Crypt_* class}
*/
public function setKey(string $key): void
{
if ($this->explicit_key_length !== false && strlen($key) != $this->explicit_key_length) {
throw new InconsistentSetupException('Key length has already been set to ' . $this->explicit_key_length . ' bytes and this key is ' . strlen($key) . ' bytes');
}
$this->key = $key;
$this->key_length = strlen($key);
$this->setEngine();
}
/**
* Sets the password.
*
* Depending on what $method is set to, setPassword()'s (optional) parameters are as follows:
* {@link http://en.wikipedia.org/wiki/PBKDF2 pbkdf2} or pbkdf1:
* $hash, $salt, $count, $dkLen
*
* Where $hash (default = sha1) currently supports the following hashes: see: Crypt/Hash.php
* {@link https://en.wikipedia.org/wiki/Bcrypt bcypt}:
* $salt, $rounds, $keylen
*
* This is a modified version of bcrypt used by OpenSSH.
*
* {@internal Could, but not must, extend by the child Crypt_* class}
*
* @param int|string ...$func_args
* @throws LengthException if pbkdf1 is being used and the derived key length exceeds the hash length
* @throws RuntimeException if bcrypt is being used and a salt isn't provided
* @see Crypt/Hash.php
*/
public function setPassword(string $password, string $method = 'pbkdf2', ...$func_args): bool
{
$key = '';
$method = strtolower($method);
switch ($method) {
case 'bcrypt':
if (!isset($func_args[2])) {
throw new RuntimeException('A salt must be provided for bcrypt to work');
}
$salt = $func_args[0];
$rounds = $func_args[1] ?? 16;
$keylen = $func_args[2] ?? $this->key_length;
$key = Blowfish::bcrypt_pbkdf($password, $salt, $keylen + $this->block_size, $rounds);
$this->setKey(substr($key, 0, $keylen));
$this->setIV(substr($key, $keylen));
return true;
case 'pkcs12': // from https://tools.ietf.org/html/rfc7292#appendix-B.2
case 'pbkdf1':
case 'pbkdf2':
// Hash function
$hash = isset($func_args[0]) ? strtolower($func_args[0]) : 'sha1';
$hashObj = new Hash();
$hashObj->setHash($hash);
// WPA and WPA2 use the SSID as the salt
$salt = $func_args[1] ?? $this->password_default_salt;
// RFC2898#section-4.2 uses 1,000 iterations by default
// WPA and WPA2 use 4,096.
$count = $func_args[2] ?? 1000;
// Keylength
if (isset($func_args[3])) {
if ($func_args[3] <= 0) {
throw new LengthException('Derived key length cannot be longer 0 or less');
}
$dkLen = $func_args[3];
} else {
$key_length = $this->explicit_key_length !== false ? $this->explicit_key_length : $this->key_length;
$dkLen = $method == 'pbkdf1' ? 2 * $key_length : $key_length;
}
switch (true) {
case $method == 'pkcs12':
/*
In this specification, however, all passwords are created from
BMPStrings with a NULL terminator. This means that each character in
the original BMPString is encoded in 2 bytes in big-endian format
(most-significant byte first). There are no Unicode byte order
marks. The 2 bytes produced from the last character in the BMPString
are followed by 2 additional bytes with the value 0x00.
-- https://tools.ietf.org/html/rfc7292#appendix-B.1
*/
$password = "\0" . chunk_split($password, 1, "\0") . "\0";
/*
This standard specifies 3 different values for the ID byte mentioned
above:
1. If ID=1, then the pseudorandom bits being produced are to be used
as key material for performing encryption or decryption.
2. If ID=2, then the pseudorandom bits being produced are to be used
as an IV (Initial Value) for encryption or decryption.
3. If ID=3, then the pseudorandom bits being produced are to be used
as an integrity key for MACing.
*/
// Construct a string, D (the "diversifier"), by concatenating v/8
// copies of ID.
$blockLength = $hashObj->getBlockLengthInBytes();
$d1 = str_repeat(chr(1), $blockLength);
$d2 = str_repeat(chr(2), $blockLength);
$s = '';
if (strlen($salt)) {
while (strlen($s) < $blockLength) {
$s .= $salt;
}
}
$s = substr($s, 0, $blockLength);
$p = '';
if (strlen($password)) {
while (strlen($p) < $blockLength) {
$p .= $password;
}
}
$p = substr($p, 0, $blockLength);
$i = $s . $p;
$this->setKey(self::pkcs12helper($dkLen, $hashObj, $i, $d1, $count));
if ($this->usesIV()) {
$this->setIV(self::pkcs12helper($this->block_size, $hashObj, $i, $d2, $count));
}
return true;
case $method == 'pbkdf1':
if ($dkLen > $hashObj->getLengthInBytes()) {
throw new LengthException('Derived key length cannot be longer than the hash length');
}
$t = $password . $salt;
for ($i = 0; $i < $count; ++$i) {
$t = $hashObj->hash($t);
}
$key = substr($t, 0, $dkLen);
$this->setKey(substr($key, 0, $dkLen >> 1));
if ($this->usesIV()) {
$this->setIV(substr($key, $dkLen >> 1));
}
return true;
case !in_array($hash, hash_algos()):
$i = 1;
$hashObj->setKey($password);
while (strlen($key) < $dkLen) {
$f = $u = $hashObj->hash($salt . pack('N', $i++));
for ($j = 2; $j <= $count; ++$j) {
$u = $hashObj->hash($u);
$f ^= $u;
}
$key .= $f;
}
$key = substr($key, 0, $dkLen);
break;
default:
$key = hash_pbkdf2($hash, $password, $salt, $count, $dkLen, true);
}
break;
default:
throw new UnsupportedAlgorithmException($method . ' is not a supported password hashing method');
}
$this->setKey($key);
return true;
}
/**
* PKCS#12 KDF Helper Function
*
* As discussed here:
*
* {@link https://tools.ietf.org/html/rfc7292#appendix-B}
*
* @return string $a
* @see self::setPassword()
*/
private static function pkcs12helper(int $n, Hash $hashObj, string $i, string $d, int $count): string
{
static $one;
if (!isset($one)) {
$one = new BigInteger(1);
}
$blockLength = $hashObj->getBlockLength() >> 3;
$c = ceil($n / $hashObj->getLengthInBytes());
$a = '';
for ($j = 1; $j <= $c; $j++) {
$ai = $d . $i;
for ($k = 0; $k < $count; $k++) {
$ai = $hashObj->hash($ai);
}
$b = '';
while (strlen($b) < $blockLength) {
$b .= $ai;
}
$b = substr($b, 0, $blockLength);
$b = new BigInteger($b, 256);
$newi = '';
for ($k = 0; $k < strlen($i); $k += $blockLength) {
$temp = substr($i, $k, $blockLength);
$temp = new BigInteger($temp, 256);
$temp->setPrecision($blockLength << 3);
$temp = $temp->add($b);
$temp = $temp->add($one);
$newi .= $temp->toBytes(false);
}
$i = $newi;
$a .= $ai;
}
return substr($a, 0, $n);
}
/**
* Encrypts a message.
*
* $plaintext will be padded with additional bytes such that it's length is a multiple of the block size. Other cipher
* implementations may or may not pad in the same manner. Other common approaches to padding and the reasons why it's
* necessary are discussed in the following
* URL:
*
* {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html}
*
* An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does.
* strlen($plaintext) will still need to be a multiple of the block size, however, arbitrary values can be added to make it that
* length.
*
* {@internal Could, but not must, extend by the child Crypt_* class}
*
* @return string $ciphertext
* @see self::decrypt()
*/
public function encrypt(string $plaintext): string
{
if ($this->paddable) {
$plaintext = $this->pad($plaintext);
}
$this->setup();
if ($this->mode == self::MODE_GCM) {
$oldIV = $this->iv;
Strings::increment_str($this->iv);
$cipher = new static('ctr');
$cipher->setKey($this->key);
$cipher->setIV($this->iv);
$ciphertext = $cipher->encrypt($plaintext);
$s = $this->ghash(
self::nullPad128($this->aad) .
self::nullPad128($ciphertext) .
self::len64($this->aad) .
self::len64($ciphertext)