-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathCrypto.php
592 lines (558 loc) · 16.9 KB
/
Crypto.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
<?php
declare(strict_types=1);
namespace ParagonIE\Halite\Symmetric;
use Error;
use ParagonIE\ConstantTime\Binary;
use ParagonIE\Halite\Alerts\{
CannotPerformOperation,
InvalidDigestLength,
InvalidMessage,
InvalidSignature,
InvalidType
};
use ParagonIE\Halite\{
Config as BaseConfig,
Halite,
Symmetric\Config as SymmetricConfig,
Util
};
use ParagonIE\HiddenString\HiddenString;
use RangeException;
use SodiumException;
use Throwable;
use TypeError;
use const
SODIUM_CRYPTO_AUTH_KEYBYTES,
SODIUM_CRYPTO_SECRETBOX_KEYBYTES,
SODIUM_CRYPTO_STREAM_NONCEBYTES;
use function
hash_equals,
is_callable,
is_null,
random_bytes,
sodium_crypto_generichash,
sodium_crypto_stream_xchacha20_xor,
sodium_crypto_stream_xor,
str_repeat;
/**
* Class Crypto
*
* Encapsulates symmetric-key cryptography
*
* This library makes heavy use of return-type declarations,
* which are a PHP 7 only feature. Read more about them here:
*
* @ref https://www.php.net/manual/en/functions.returning-values.php#functions.returning-values.type-declaration
*
* @package ParagonIE\Halite\Symmetric
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://www.mozilla.org/en-US/MPL/2.0/.
*/
final class Crypto
{
/**
* Don't allow this to be instantiated.
*
* @throws Error
* @codeCoverageIgnore
*/
final private function __construct()
{
throw new Error('Do not instantiate');
}
/**
* Authenticate a string
*
* @param string $message
* @param AuthenticationKey $secretKey
* @param string|bool $encoding
*
* @return string
*
* @throws InvalidMessage
* @throws InvalidType
* @throws SodiumException
* @throws TypeError
*/
public static function authenticate(
string $message,
AuthenticationKey $secretKey,
bool|string $encoding = Halite::ENCODE_BASE64URLSAFE
): string {
$config = SymmetricConfig::getConfig(
Halite::HALITE_VERSION,
'auth'
);
$mac = self::calculateMAC(
$message,
$secretKey->getRawKeyMaterial(),
$config
);
$encoder = Halite::chooseEncoder($encoding);
if ($encoder) {
return (string) $encoder($mac);
}
return $mac;
}
/**
* Decrypt a message using the Halite encryption protocol
*
* @param string $ciphertext
* @param EncryptionKey $secretKey
* @param string|bool $encoding
*
* @return HiddenString
*
* @throws CannotPerformOperation
* @throws InvalidDigestLength
* @throws InvalidMessage
* @throws InvalidSignature
* @throws InvalidType
* @throws SodiumException
* @throws TypeError
*/
public static function decrypt(
string $ciphertext,
EncryptionKey $secretKey,
bool|string $encoding = Halite::ENCODE_BASE64URLSAFE
): HiddenString {
return self::decryptWithAD(
$ciphertext,
$secretKey,
'',
$encoding
);
}
/**
* Decrypt a message using the Halite encryption protocol
*
* Verifies the MAC before decryption
* - Halite 5+ verifies the BLAKE2b-MAC before decrypting with XChaCha20
* - Halite 4 and below verifies the BLAKE2b-MAC before decrypting with XSalsa20
*
* You don't need to worry about chosen-ciphertext attacks.
* You don't need to worry about Invisible Salamanders.
* You don't need to worry about timing attacks on MAC validation.
*
* @param string $ciphertext
* @param EncryptionKey $secretKey
* @param string $additionalData
* @param string|bool $encoding
*
* @return HiddenString
*
* @throws CannotPerformOperation
* @throws InvalidDigestLength
* @throws InvalidMessage
* @throws InvalidSignature
* @throws InvalidType
* @throws SodiumException
* @throws TypeError
*/
public static function decryptWithAD(
string $ciphertext,
EncryptionKey $secretKey,
string $additionalData = '',
bool|string $encoding = Halite::ENCODE_BASE64URLSAFE
): HiddenString {
$decoder = Halite::chooseEncoder($encoding, true);
if (is_callable($decoder)) {
// We were given encoded data:
// @codeCoverageIgnoreStart
try {
/** @var string $ciphertext */
$ciphertext = $decoder($ciphertext);
} catch (RangeException $ex) {
throw new InvalidMessage(
'Invalid character encoding'
);
}
// @codeCoverageIgnoreEnd
}
/**
* @var string $version
* @var Config $config
* @var string $salt
* @var string $nonce
* @var string $encrypted
* @var string $auth
*/
[
$version,
$config,
$salt,
$nonce,
$encrypted,
$auth
] = self::unpackMessageForDecryption($ciphertext);
/* Split our key into two keys: One for encryption, the other for
authentication. By using separate keys, we can reasonably dismiss
likely cross-protocol attacks.
This uses salted HKDF to split the keys, which is why we need the
salt in the first place. */
/** @var array<int, string> $split */
$split = Util::splitKeys($secretKey, $salt, $config);
$encKey = $split[0];
$authKey = $split[1];
// Check the MAC first
if ($config->USE_PAE) {
$verified = self::verifyMAC(
$auth,
Util::PAE($version, $salt, $nonce, $additionalData, $encrypted),
$authKey,
$config
);
} else {
$verified = self::verifyMAC(
// @codeCoverageIgnoreStart
$auth,
$version .
$salt .
$nonce .
$additionalData .
$encrypted,
// @codeCoverageIgnoreEnd
$authKey,
$config
);
}
if (!$verified) {
throw new InvalidMessage(
'Invalid message authentication code'
);
}
Util::memzero($salt);
Util::memzero($authKey);
// crypto_stream_xor() can be used to encrypt and decrypt
if ($config->ENC_ALGO === 'XChaCha20') {
$plaintext = sodium_crypto_stream_xchacha20_xor($encrypted, $nonce, $encKey);
} else {
$plaintext = sodium_crypto_stream_xor($encrypted, $nonce, $encKey);
}
Util::memzero($encrypted);
Util::memzero($nonce);
Util::memzero($encKey);
return new HiddenString($plaintext);
}
/**
* Encrypt a message using the Halite encryption protocol
*
* @param HiddenString $plaintext
* @param EncryptionKey $secretKey
* @param string|bool $encoding
*
* @return string
*
* @throws CannotPerformOperation
* @throws InvalidDigestLength
* @throws InvalidMessage
* @throws InvalidType
* @throws SodiumException
* @throws TypeError
*/
public static function encrypt(
HiddenString $plaintext,
EncryptionKey $secretKey,
bool|string $encoding = Halite::ENCODE_BASE64URLSAFE
): string {
return self::encryptWithAD(
$plaintext,
$secretKey,
'',
$encoding
);
}
/**
* Encrypt a message using the Halite encryption protocol
*
* Encrypt then MAC.
* - Halite 5+ uses XChaCha20 then BLAKE2b-MAC
* - Halite 4 and below use XSalsa20 then BLAKE2b-MAC
*
* You don't need to worry about chosen-ciphertext attacks.
* You don't need to worry about Invisible Salamanders.
*
* @param HiddenString $plaintext
* @param EncryptionKey $secretKey
* @param string $additionalData
* @param bool|string $encoding
*
* @return string
*
* @throws CannotPerformOperation
* @throws InvalidDigestLength
* @throws InvalidMessage
* @throws InvalidType
* @throws SodiumException
* @throws TypeError
*/
public static function encryptWithAD(
HiddenString $plaintext,
EncryptionKey $secretKey,
string $additionalData = '',
bool|string $encoding = Halite::ENCODE_BASE64URLSAFE
): string {
$config = SymmetricConfig::getConfig(Halite::HALITE_VERSION, 'encrypt');
// Generate a nonce and HKDF salt:
// @codeCoverageIgnoreStart
try {
$nonce = random_bytes(\SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$salt = random_bytes((int) $config->HKDF_SALT_LEN);
} catch (Throwable $ex) {
throw new CannotPerformOperation($ex->getMessage());
}
// @codeCoverageIgnoreEnd
/* Split our key into two keys: One for encryption, the other for
authentication. By using separate keys, we can reasonably dismiss
likely cross-protocol attacks.
This uses salted HKDF to split the keys, which is why we need the
salt in the first place. */
[$encKey, $authKey] = Util::splitKeys($secretKey, $salt, $config);
// Encrypt our message with the encryption key:
if ($config->ENC_ALGO === 'XChaCha20') {
$encrypted = sodium_crypto_stream_xchacha20_xor(
$plaintext->getString(),
$nonce,
$encKey
);
} else {
$encrypted = sodium_crypto_stream_xor(
$plaintext->getString(),
$nonce,
$encKey
);
}
Util::memzero($encKey);
// Calculate an authentication tag:
if ($config->USE_PAE) {
$auth = self::calculateMAC(
Util::PAE(
Halite::HALITE_VERSION,
$salt,
$nonce,
$additionalData,
$encrypted
),
$authKey,
$config
);
} else {
$auth = self::calculateMAC(
Halite::HALITE_VERSION . $salt . $nonce . $additionalData . $encrypted,
$authKey,
$config
);
}
Util::memzero($authKey);
$message = Halite::HALITE_VERSION . $salt . $nonce . $encrypted . $auth;
// Wipe every superfluous piece of data from memory
Util::memzero($nonce);
Util::memzero($salt);
Util::memzero($encrypted);
Util::memzero($auth);
$encoder = Halite::chooseEncoder($encoding);
if ($encoder) {
return (string) $encoder($message);
}
return $message;
}
/**
* Unpack a message string into an array (assigned to variables via list()).
*
* Should return exactly 6 elements.
*
* @param string $ciphertext
*
* @return array<int, mixed>
*
* @throws InvalidMessage
* @throws TypeError
* @codeCoverageIgnore
*/
public static function unpackMessageForDecryption(string $ciphertext): array
{
$length = Binary::safeStrlen($ciphertext);
// Fail fast on invalid messages
if ($length < Halite::VERSION_TAG_LEN) {
throw new InvalidMessage(
'Message is too short'
);
}
// The first 4 bytes are reserved for the version size
$version = Binary::safeSubstr(
$ciphertext,
0,
Halite::VERSION_TAG_LEN
);
$config = SymmetricConfig::getConfig($version, 'encrypt');
if ($length < $config->SHORTEST_CIPHERTEXT_LENGTH) {
throw new InvalidMessage(
'Message is too short'
);
}
// The salt is used for key splitting (via HKDF)
$salt = Binary::safeSubstr(
$ciphertext,
Halite::VERSION_TAG_LEN,
(int) $config->HKDF_SALT_LEN
);
// This is the nonce (we authenticated it):
$nonce = Binary::safeSubstr(
$ciphertext,
// 36:
Halite::VERSION_TAG_LEN + (int) $config->HKDF_SALT_LEN,
// 24:
SODIUM_CRYPTO_STREAM_NONCEBYTES
);
// This is the crypto_stream_xor()ed ciphertext
$encrypted = Binary::safeSubstr(
$ciphertext,
// 60:
Halite::VERSION_TAG_LEN +
(int) $config->HKDF_SALT_LEN +
SODIUM_CRYPTO_STREAM_NONCEBYTES,
// $length - 124
$length - (
Halite::VERSION_TAG_LEN +
(int) $config->HKDF_SALT_LEN +
SODIUM_CRYPTO_STREAM_NONCEBYTES +
(int) $config->MAC_SIZE
)
);
// $auth is the last 32 bytes
$auth = Binary::safeSubstr(
$ciphertext,
$length - (int) $config->MAC_SIZE
);
// We don't need this anymore.
Util::memzero($ciphertext);
// Now we return the pieces in a specific order:
return [$version, $config, $salt, $nonce, $encrypted, $auth];
}
/**
* Verify the authenticity of a message, given a shared MAC key
*
* @param string $message
* @param AuthenticationKey $secretKey
* @param string $mac
* @param string|bool $encoding
* @param ?SymmetricConfig $config
*
* @return bool
*
* @throws InvalidMessage
* @throws InvalidSignature
* @throws InvalidType
* @throws SodiumException
* @throws TypeError
*/
public static function verify(
string $message,
AuthenticationKey $secretKey,
string $mac,
string|bool $encoding = Halite::ENCODE_BASE64URLSAFE,
?SymmetricConfig $config = null
): bool {
$decoder = Halite::chooseEncoder($encoding, true);
if ($decoder) {
// We were given hex data:
/** @var string $mac */
$mac = $decoder($mac);
}
if (is_null($config)) {
// Default to the current version
$config = SymmetricConfig::getConfig(
Halite::HALITE_VERSION,
'auth'
);
}
try {
return self::verifyMAC(
$mac,
$message,
$secretKey->getRawKeyMaterial(),
$config
);
// @codeCoverageIgnoreStart
} catch (InvalidMessage $ex) {
return false;
// @codeCoverageIgnoreEnd
}
}
/**
* Calculate a MAC. This is used internally.
*
* @param string $message
* @param string $authKey
* @param SymmetricConfig $config
*
* @return string
*
* @throws InvalidMessage
* @throws SodiumException
*/
protected static function calculateMAC(
string $message,
string $authKey,
SymmetricConfig $config
): string {
if ($config->MAC_ALGO === 'BLAKE2b') {
return sodium_crypto_generichash(
$message,
$authKey,
(int) $config->MAC_SIZE
);
}
// @codeCoverageIgnoreStart
throw new InvalidMessage(
'Invalid Halite version'
);
// @codeCoverageIgnoreEnd
}
/**
* Verify a Message Authentication Code (MAC) of a message, with a shared
* key.
*
* @param string $mac Message Authentication Code
* @param string $message The message to verify
* @param string $authKey Authentication key (symmetric)
* @param SymmetricConfig $config Configuration object
*
* @return bool
*
* @throws InvalidMessage
* @throws InvalidSignature
* @throws SodiumException
*/
protected static function verifyMAC(
string $mac,
string $message,
string $authKey,
SymmetricConfig $config
): bool {
if (Binary::safeStrlen($mac) !== $config->MAC_SIZE) {
// @codeCoverageIgnoreStart
throw new InvalidSignature(
'Argument 1: Message Authentication Code is not the correct length; is it encoded?'
);
// @codeCoverageIgnoreEnd
}
if ($config->MAC_ALGO === 'BLAKE2b') {
$calc = sodium_crypto_generichash(
$message,
$authKey,
(int) $config->MAC_SIZE
);
$res = hash_equals($mac, $calc);
Util::memzero($calc);
return $res;
}
// @codeCoverageIgnoreStart
throw new InvalidMessage(
'Invalid Halite version'
);
// @codeCoverageIgnoreEnd
}
}