Debian Codegraph @

lib/3rdParty/composer/paragonie/sodium_compat/src/File.php

raw symbols SCIP
1 <?php
2 declare(strict_types=1);
3
4 if (class_exists('ParagonIE_Sodium_File', false)) {
5 return;
6 }
7 /**
8 * Class ParagonIE_Sodium_File
9 */
10 class ParagonIE_Sodium_File extends ParagonIE_Sodium_Core_Util
11 {
12 /* PHP's default buffer size is 8192 for fread()/fwrite(). */
13 const BUFFER_SIZE = 8192;
14
15 /**
16 * Box a file (rather than a string). Uses less memory than
17 * ParagonIE_Sodium_Compat::crypto_box(), but produces
18 * the same result.
19 *
20 * @param string $inputFile Absolute path to a file on the filesystem
21 * @param string $outputFile Absolute path to a file on the filesystem
22 * @param string $nonce Number to be used only once
23 * @param string $keyPair ECDH secret key and ECDH public key concatenated
24 *
25 * @return bool
26 * @throws SodiumException
27 * @throws TypeError
28 */
29 public static function box(
30 string $inputFile,
31 string $outputFile,
32 string $nonce,
33 #[SensitiveParameter]
34 string $keyPair
35 ): bool {
36 if (self::strlen($nonce) !== ParagonIE_Sodium_Compat::CRYPTO_BOX_NONCEBYTES) {
37 throw new TypeError('Argument 3 must be CRYPTO_BOX_NONCEBYTES bytes');
38 }
39 if (self::strlen($keyPair) !== ParagonIE_Sodium_Compat::CRYPTO_BOX_KEYPAIRBYTES) {
40 throw new TypeError('Argument 4 must be CRYPTO_BOX_KEYPAIRBYTES bytes');
41 }
42
43 $size = @filesize($inputFile);
44 if (!is_int($size)) {
45 throw new SodiumException('Could not obtain the file size');
46 }
47
48 $ifp = fopen($inputFile, 'rb');
49 if (!is_resource($ifp)) {
50 throw new SodiumException('Could not open input file for reading');
51 }
52
53 $ofp = @fopen($outputFile, 'wb');
54 if (!is_resource($ofp)) {
55 fclose($ifp);
56 throw new SodiumException('Could not open output file for writing');
57 }
58
59 $res = self::box_encrypt($ifp, $ofp, $size, $nonce, $keyPair);
60 fclose($ifp);
61 fclose($ofp);
62 return $res;
63 }
64
65 /**
66 * Open a boxed file (rather than a string). Uses less memory than
67 * ParagonIE_Sodium_Compat::crypto_box_open(), but produces
68 * the same result.
69 *
70 * Warning: Does not protect against TOCTOU attacks. You should
71 * just load the file into memory and use crypto_box_open() if
72 * you are worried about those.
73 *
74 * @param string $inputFile
75 * @param string $outputFile
76 * @param string $nonce
77 * @param string $keypair
78 * @return bool
79 * @throws SodiumException
80 * @throws TypeError
81 */
82 public static function box_open(
83 string $inputFile,
84 string $outputFile,
85 string $nonce,
86 #[SensitiveParameter]
87 string $keypair
88 ): bool {
89 /* Input validation: */
90 if (self::strlen($nonce) !== ParagonIE_Sodium_Compat::CRYPTO_BOX_NONCEBYTES) {
91 throw new TypeError('Argument 4 must be CRYPTO_BOX_NONCEBYTES bytes');
92 }
93 if (self::strlen($keypair) !== ParagonIE_Sodium_Compat::CRYPTO_BOX_KEYPAIRBYTES) {
94 throw new TypeError('Argument 4 must be CRYPTO_BOX_KEYPAIRBYTES bytes');
95 }
96
97 if (!file_exists($inputFile)) {
98 throw new SodiumException('Input file does not exist');
99 }
100 $size = filesize($inputFile);
101 if (!is_int($size)) {
102 throw new SodiumException('Could not obtain the file size');
103 }
104
105 $ifp = fopen($inputFile, 'rb');
106 if (!is_resource($ifp)) {
107 throw new SodiumException('Could not open input file for reading');
108 }
109
110 $ofp = @fopen($outputFile, 'wb');
111 if (!is_resource($ofp)) {
112 fclose($ifp);
113 throw new SodiumException('Could not open output file for writing');
114 }
115
116 $res = self::box_decrypt($ifp, $ofp, $size, $nonce, $keypair);
117 fclose($ifp);
118 fclose($ofp);
119 try {
120 ParagonIE_Sodium_Compat::memzero($nonce);
121 ParagonIE_Sodium_Compat::memzero($ephKeypair);
122 } catch (SodiumException) {
123 if (isset($ephKeypair)) {
124 unset($ephKeypair);
125 }
126 }
127 return $res;
128 }
129
130 /**
131 * Seal a file (rather than a string). Uses less memory than
132 * ParagonIE_Sodium_Compat::crypto_box_seal(), but produces
133 * the same result.
134 *
135 * @param string $inputFile Absolute path to a file on the filesystem
136 * @param string $outputFile Absolute path to a file on the filesystem
137 * @param string $publicKey ECDH public key
138 *
139 * @return bool
140 * @throws SodiumException
141 * @throws TypeError
142 */
143 public static function box_seal(
144 string $inputFile,
145 string $outputFile,
146 string $publicKey
147 ): bool {
148 /* Input validation: */
149 if (self::strlen($publicKey) !== ParagonIE_Sodium_Compat::CRYPTO_BOX_PUBLICKEYBYTES) {
150 throw new TypeError('Argument 3 must be CRYPTO_BOX_PUBLICKEYBYTES bytes');
151 }
152
153 if (!file_exists($inputFile)) {
154 throw new SodiumException('Input file does not exist');
155 }
156 $size = filesize($inputFile);
157 if (!is_int($size)) {
158 throw new SodiumException('Could not obtain the file size');
159 }
160
161 $ifp = fopen($inputFile, 'rb');
162 if (!is_resource($ifp)) {
163 throw new SodiumException('Could not open input file for reading');
164 }
165
166 $ofp = @fopen($outputFile, 'wb');
167 if (!is_resource($ofp)) {
168 fclose($ifp);
169 throw new SodiumException('Could not open output file for writing');
170 }
171
172 $ephKeypair = ParagonIE_Sodium_Compat::crypto_box_keypair();
173 $msgKeypair = ParagonIE_Sodium_Compat::crypto_box_keypair_from_secretkey_and_publickey(
174 ParagonIE_Sodium_Compat::crypto_box_secretkey($ephKeypair),
175 $publicKey
176 );
177 $ephemeralPK = ParagonIE_Sodium_Compat::crypto_box_publickey($ephKeypair);
178 $nonce = ParagonIE_Sodium_Compat::crypto_generichash(
179 $ephemeralPK . $publicKey,
180 '',
181 24
182 );
183
184 $firstWrite = fwrite(
185 $ofp,
186 $ephemeralPK,
187 ParagonIE_Sodium_Compat::CRYPTO_BOX_PUBLICKEYBYTES
188 );
189 if (!is_int($firstWrite)) {
190 fclose($ifp);
191 fclose($ofp);
192 ParagonIE_Sodium_Compat::memzero($ephKeypair);
193 throw new SodiumException('Could not write to output file');
194 }
195 if ($firstWrite !== ParagonIE_Sodium_Compat::CRYPTO_BOX_PUBLICKEYBYTES) {
196 ParagonIE_Sodium_Compat::memzero($ephKeypair);
197 fclose($ifp);
198 fclose($ofp);
199 throw new SodiumException('Error writing public key to output file');
200 }
201
202 $res = self::box_encrypt($ifp, $ofp, $size, $nonce, $msgKeypair);
203 fclose($ifp);
204 fclose($ofp);
205 try {
206 ParagonIE_Sodium_Compat::memzero($nonce);
207 ParagonIE_Sodium_Compat::memzero($ephKeypair);
208 } catch (SodiumException) {
209 /** @psalm-suppress PossiblyUndefinedVariable */
210 unset($ephKeypair);
211 }
212 return $res;
213 }
214
215 /**
216 * Open a sealed file (rather than a string). Uses less memory than
217 * ParagonIE_Sodium_Compat::crypto_box_seal_open(), but produces
218 * the same result.
219 *
220 * Warning: Does not protect against TOCTOU attacks. You should
221 * just load the file into memory and use crypto_box_seal_open() if
222 * you are worried about those.
223 *
224 * @param string $inputFile
225 * @param string $outputFile
226 * @param string $ecdhKeypair
227 * @return bool
228 * @throws SodiumException
229 * @throws TypeError
230 */
231 public static function box_seal_open(
232 string $inputFile,
233 string $outputFile,
234 #[SensitiveParameter]
235 string $ecdhKeypair
236 ): bool {
237 /* Input validation: */
238 if (self::strlen($ecdhKeypair) !== ParagonIE_Sodium_Compat::CRYPTO_BOX_KEYPAIRBYTES) {
239 throw new TypeError('Argument 3 must be CRYPTO_BOX_KEYPAIRBYTES bytes');
240 }
241
242 $publicKey = ParagonIE_Sodium_Compat::crypto_box_publickey($ecdhKeypair);
243
244 if (!file_exists($inputFile)) {
245 throw new SodiumException('Input file does not exist');
246 }
247 $size = filesize($inputFile);
248 if (!is_int($size)) {
249 throw new SodiumException('Could not obtain the file size');
250 }
251
252 $ifp = fopen($inputFile, 'rb');
253 if (!is_resource($ifp)) {
254 throw new SodiumException('Could not open input file for reading');
255 }
256
257 $ofp = @fopen($outputFile, 'wb');
258 if (!is_resource($ofp)) {
259 fclose($ifp);
260 throw new SodiumException('Could not open output file for writing');
261 }
262
263 $ephemeralPK = fread($ifp, ParagonIE_Sodium_Compat::CRYPTO_BOX_PUBLICKEYBYTES);
264 if (!is_string($ephemeralPK)) {
265 throw new SodiumException('Could not read input file');
266 }
267 if (self::strlen($ephemeralPK) !== ParagonIE_Sodium_Compat::CRYPTO_BOX_PUBLICKEYBYTES) {
268 fclose($ifp);
269 fclose($ofp);
270 throw new SodiumException('Could not read public key from sealed file');
271 }
272
273 $nonce = ParagonIE_Sodium_Compat::crypto_generichash(
274 $ephemeralPK . $publicKey,
275 '',
276 24
277 );
278 $msgKeypair = ParagonIE_Sodium_Compat::crypto_box_keypair_from_secretkey_and_publickey(
279 ParagonIE_Sodium_Compat::crypto_box_secretkey($ecdhKeypair),
280 $ephemeralPK
281 );
282
283 $res = self::box_decrypt($ifp, $ofp, $size, $nonce, $msgKeypair);
284 fclose($ifp);
285 fclose($ofp);
286 try {
287 ParagonIE_Sodium_Compat::memzero($nonce);
288 ParagonIE_Sodium_Compat::memzero($ephKeypair);
289 } catch (SodiumException) {
290 if (isset($ephKeypair)) {
291 unset($ephKeypair);
292 }
293 }
294 return $res;
295 }
296
297 /**
298 * Calculate the BLAKE2b hash of a file.
299 *
300 * @param string $filePath Absolute path to a file on the filesystem
301 * @param string|null $key BLAKE2b key
302 * @param int $outputLength Length of hash output
303 *
304 * @return string BLAKE2b hash
305 * @throws SodiumException
306 * @throws TypeError
307 */
308 public static function generichash(
309 string $filePath,
310 #[SensitiveParameter]
311 ?string $key = '',
312 int $outputLength = 32
313 ): string {
314 if (is_null($key)) {
315 $key = '';
316 }
317
318 /* Input validation: */
319 if (!empty($key)) {
320 if (self::strlen($key) < ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_KEYBYTES_MIN) {
321 throw new TypeError('Argument 2 must be at least CRYPTO_GENERICHASH_KEYBYTES_MIN bytes');
322 }
323 if (self::strlen($key) > ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_KEYBYTES_MAX) {
324 throw new TypeError('Argument 2 must be at most CRYPTO_GENERICHASH_KEYBYTES_MAX bytes');
325 }
326 }
327 if ($outputLength < ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_BYTES_MIN) {
328 throw new SodiumException('Argument 3 must be at least CRYPTO_GENERICHASH_BYTES_MIN');
329 }
330 if ($outputLength > ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_BYTES_MAX) {
331 throw new SodiumException('Argument 3 must be at least CRYPTO_GENERICHASH_BYTES_MAX');
332 }
333
334 if (!file_exists($filePath)) {
335 throw new SodiumException('File does not exist');
336 }
337 $size = filesize($filePath);
338 if (!is_int($size)) {
339 throw new SodiumException('Could not obtain the file size');
340 }
341
342 $fp = fopen($filePath, 'rb');
343 if (!is_resource($fp)) {
344 throw new SodiumException('Could not open input file for reading');
345 }
346 $ctx = ParagonIE_Sodium_Compat::crypto_generichash_init($key, $outputLength);
347 while ($size > 0) {
348 $blockSize = min($size, 64);
349 $read = fread($fp, $blockSize);
350 if (!is_string($read)) {
351 throw new SodiumException('Could not read input file');
352 }
353 ParagonIE_Sodium_Compat::crypto_generichash_update($ctx, $read);
354 $size -= $blockSize;
355 }
356
357 fclose($fp);
358 return ParagonIE_Sodium_Compat::crypto_generichash_final($ctx, $outputLength);
359 }
360
361 /**
362 * Encrypt a file (rather than a string). Uses less memory than
363 * ParagonIE_Sodium_Compat::crypto_secretbox(), but produces
364 * the same result.
365 *
366 * @param string $inputFile Absolute path to a file on the filesystem
367 * @param string $outputFile Absolute path to a file on the filesystem
368 * @param string $nonce Number to be used only once
369 * @param string $key Encryption key
370 *
371 * @return bool
372 * @throws SodiumException
373 * @throws TypeError
374 */
375 public static function secretbox(
376 string $inputFile,
377 string $outputFile,
378 string $nonce,
379 #[SensitiveParameter]
380 string $key
381 ): bool {
382 /* Input validation: */
383 if (self::strlen($nonce) !== ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_NONCEBYTES) {
384 throw new TypeError('Argument 3 must be CRYPTO_SECRETBOX_NONCEBYTES bytes');
385 }
386 if (self::strlen($key) !== ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_KEYBYTES) {
387 throw new TypeError('Argument 4 must be CRYPTO_SECRETBOX_KEYBYTES bytes');
388 }
389
390 if (!file_exists($inputFile)) {
391 throw new SodiumException('Input file does not exist');
392 }
393 $size = filesize($inputFile);
394 if (!is_int($size)) {
395 throw new SodiumException('Could not obtain the file size');
396 }
397
398 $ifp = fopen($inputFile, 'rb');
399 if (!is_resource($ifp)) {
400 throw new SodiumException('Could not open input file for reading');
401 }
402
403 $ofp = @fopen($outputFile, 'wb');
404 if (!is_resource($ofp)) {
405 fclose($ifp);
406 throw new SodiumException('Could not open output file for writing');
407 }
408
409 $res = self::secretbox_encrypt($ifp, $ofp, $size, $nonce, $key);
410 fclose($ifp);
411 fclose($ofp);
412 return $res;
413 }
414
415 /**
416 * Seal a file (rather than a string). Uses less memory than
417 * ParagonIE_Sodium_Compat::crypto_secretbox_open(), but produces
418 * the same result.
419 *
420 * Warning: Does not protect against TOCTOU attacks. You should
421 * just load the file into memory and use crypto_secretbox_open() if
422 * you are worried about those.
423 *
424 * @param string $inputFile
425 * @param string $outputFile
426 * @param string $nonce
427 * @param string $key
428 * @return bool
429 * @throws SodiumException
430 * @throws TypeError
431 */
432 public static function secretbox_open(
433 string $inputFile,
434 string $outputFile,
435 string $nonce,
436 #[SensitiveParameter]
437 string $key
438 ): bool {
439 /* Input validation: */
440 if (self::strlen($nonce) !== ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_NONCEBYTES) {
441 throw new TypeError('Argument 3 must be CRYPTO_SECRETBOX_NONCEBYTES bytes');
442 }
443 if (self::strlen($key) !== ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_KEYBYTES) {
444 throw new TypeError('Argument 4 must be CRYPTO_SECRETBOX_KEYBYTES bytes');
445 }
446
447 if (!file_exists($inputFile)) {
448 throw new SodiumException('Input file does not exist');
449 }
450 $size = filesize($inputFile);
451 if (!is_int($size)) {
452 throw new SodiumException('Could not obtain the file size');
453 }
454
455 $ifp = fopen($inputFile, 'rb');
456 if (!is_resource($ifp)) {
457 throw new SodiumException('Could not open input file for reading');
458 }
459
460 $ofp = @fopen($outputFile, 'wb');
461 if (!is_resource($ofp)) {
462 fclose($ifp);
463 throw new SodiumException('Could not open output file for writing');
464 }
465
466 $res = self::secretbox_decrypt($ifp, $ofp, $size, $nonce, $key);
467 fclose($ifp);
468 fclose($ofp);
469 try {
470 ParagonIE_Sodium_Compat::memzero($key);
471 } catch (SodiumException) {
472 /** @psalm-suppress PossiblyUndefinedVariable */
473 unset($key);
474 }
475 return $res;
476 }
477
478 /**
479 * Sign a file (rather than a string). Uses less memory than
480 * ParagonIE_Sodium_Compat::crypto_sign_detached(), but produces
481 * the same result.
482 *
483 * @param string $filePath Absolute path to a file on the filesystem
484 * @param string $secretKey Secret signing key
485 *
486 * @return string Ed25519 signature
487 * @throws SodiumException
488 * @throws TypeError
489 */
490 public static function sign(
491 string $filePath,
492 #[SensitiveParameter]
493 string $secretKey
494 ): string {
495 /* Input validation: */
496 if (self::strlen($secretKey) !== ParagonIE_Sodium_Compat::CRYPTO_SIGN_SECRETKEYBYTES) {
497 throw new TypeError('Argument 2 must be CRYPTO_SIGN_SECRETKEYBYTES bytes');
498 }
499
500 if (!file_exists($filePath)) {
501 throw new SodiumException('File does not exist');
502 }
503 $size = filesize($filePath);
504 if (!is_int($size)) {
505 throw new SodiumException('Could not obtain the file size');
506 }
507
508 $fp = fopen($filePath, 'rb');
509 if (!is_resource($fp)) {
510 throw new SodiumException('Could not open input file for reading');
511 }
512
513 /** @var string $az */
514 $az = hash('sha512', self::substr($secretKey, 0, 32), true);
515
516 $az[0] = self::intToChr(self::chrToInt($az[0]) & 248);
517 $az[31] = self::intToChr((self::chrToInt($az[31]) & 63) | 64);
518
519 $hs = hash_init('sha512');
520 hash_update($hs, self::substr($az, 32, 32));
521 $hs = self::updateHashWithFile($hs, $fp, $size);
522
523 /** @var string $nonceHash */
524 $nonceHash = hash_final($hs, true);
525
526 /** @var string $pk */
527 $pk = self::substr($secretKey, 32, 32);
528
529 /** @var string $nonce */
530 $nonce = ParagonIE_Sodium_Core_Ed25519::sc_reduce($nonceHash) . self::substr($nonceHash, 32);
531
532 /** @var string $sig */
533 $sig = ParagonIE_Sodium_Core_Ed25519::ge_p3_tobytes(
534 ParagonIE_Sodium_Core_Ed25519::ge_scalarmult_base($nonce)
535 );
536
537 $hs = hash_init('sha512');
538 hash_update($hs, self::substr($sig, 0, 32));
539 hash_update($hs, self::substr($pk, 0, 32));
540 $hs = self::updateHashWithFile($hs, $fp, $size);
541
542 /** @var string $hramHash */
543 $hramHash = hash_final($hs, true);
544
545 /** @var string $hram */
546 $hram = ParagonIE_Sodium_Core_Ed25519::sc_reduce($hramHash);
547
548 /** @var string $sigAfter */
549 $sigAfter = ParagonIE_Sodium_Core_Ed25519::sc_muladd($hram, $az, $nonce);
550
551 /** @var string $sig */
552 $sig = self::substr($sig, 0, 32) . self::substr($sigAfter, 0, 32);
553
554 try {
555 ParagonIE_Sodium_Compat::memzero($az);
556 } catch (SodiumException) {
557 $az = null;
558 }
559 fclose($fp);
560 return $sig;
561 }
562
563 /**
564 * Verify a file (rather than a string). Uses less memory than
565 * ParagonIE_Sodium_Compat::crypto_sign_verify_detached(), but
566 * produces the same result.
567 *
568 * @param string $sig Ed25519 signature
569 * @param string $filePath Absolute path to a file on the filesystem
570 * @param string $publicKey Signing public key
571 *
572 * @return bool
573 * @throws SodiumException
574 * @throws TypeError
575 * @throws Exception
576 */
577 public static function verify(string $sig, string $filePath, string $publicKey): bool
578 {
579 /* Input validation: */
580 if (self::strlen($sig) !== ParagonIE_Sodium_Compat::CRYPTO_SIGN_BYTES) {
581 throw new TypeError('Argument 1 must be CRYPTO_SIGN_BYTES bytes');
582 }
583 if (self::strlen($publicKey) !== ParagonIE_Sodium_Compat::CRYPTO_SIGN_PUBLICKEYBYTES) {
584 throw new TypeError('Argument 3 must be CRYPTO_SIGN_PUBLICKEYBYTES bytes');
585 }
586 if (self::strlen($sig) < 64) {
587 throw new SodiumException('Signature is too short');
588 }
589
590
591 /* Security checks */
592 if (
593 (ParagonIE_Sodium_Core_Ed25519::chrToInt($sig[63]) & 240)
594 &&
595 ParagonIE_Sodium_Core_Ed25519::check_S_lt_L(self::substr($sig, 32, 32))
596 ) {
597 throw new SodiumException('S < L - Invalid signature');
598 }
599 if (ParagonIE_Sodium_Core_Ed25519::small_order($sig)) {
600 throw new SodiumException('Signature is on too small of an order');
601 }
602 if ((self::chrToInt($sig[63]) & 224) !== 0) {
603 throw new SodiumException('Invalid signature');
604 }
605 $d = 0;
606 for ($i = 0; $i < 32; ++$i) {
607 $d |= self::chrToInt($publicKey[$i]);
608 }
609 if ($d === 0) {
610 throw new SodiumException('All zero public key');
611 }
612
613 if (!file_exists($filePath)) {
614 throw new SodiumException('File does not exist');
615 }
616 $size = filesize($filePath);
617 if (!is_int($size)) {
618 throw new SodiumException('Could not obtain the file size');
619 }
620
621 $fp = fopen($filePath, 'rb');
622 if (!is_resource($fp)) {
623 throw new SodiumException('Could not open input file for reading');
624 }
625
626 /* The original value of ParagonIE_Sodium_Compat::$fastMult */
627 $orig = ParagonIE_Sodium_Compat::$fastMult;
628
629 // Set ParagonIE_Sodium_Compat::$fastMult to true to speed up verification.
630 ParagonIE_Sodium_Compat::$fastMult = true;
631
632 $A = ParagonIE_Sodium_Core_Ed25519::ge_frombytes_negate_vartime($publicKey);
633 if (ParagonIE_Sodium_Core_Ed25519::small_order($publicKey)) {
634 throw new SodiumException('Public key has small order');
635 }
636 if (!ParagonIE_Sodium_Core_Ed25519::is_on_main_subgroup($A)) {
637 throw new SodiumException('Public key is not on main subgroup');
638 }
639
640 $hs = hash_init('sha512');
641 hash_update($hs, self::substr($sig, 0, 32));
642 hash_update($hs, self::substr($publicKey, 0, 32));
643
644 $hs = self::updateHashWithFile($hs, $fp, $size);
645 $hDigest = hash_final($hs, true);
646 $h = ParagonIE_Sodium_Core_Ed25519::sc_reduce($hDigest) . self::substr($hDigest, 32);
647 $R = ParagonIE_Sodium_Core_Ed25519::ge_double_scalarmult_vartime(
648 $h,
649 $A,
650 self::substr($sig, 32)
651 );
652
653 /** @var string $rcheck */
654 $rcheck = ParagonIE_Sodium_Core_Ed25519::ge_tobytes($R);
655
656 // Close the file handle
657 fclose($fp);
658
659 // Reset ParagonIE_Sodium_Compat::$fastMult to what it was before.
660 ParagonIE_Sodium_Compat::$fastMult = $orig;
661 return self::verify_32($rcheck, self::substr($sig, 0, 32));
662 }
663
664 /**
665 * @param resource $ifp
666 * @param resource $ofp
667 * @param int $mlen
668 * @param string $nonce
669 * @param string $boxKeypair
670 * @return bool
671 * @throws SodiumException
672 * @throws TypeError
673 */
674 protected static function box_encrypt(
675 $ifp,
676 $ofp,
677 int $mlen,
678 string $nonce,
679 #[SensitiveParameter]
680 string $boxKeypair
681 ): bool {
682 return self::secretbox_encrypt(
683 $ifp,
684 $ofp,
685 $mlen,
686 $nonce,
687 ParagonIE_Sodium_Crypto::box_beforenm(
688 ParagonIE_Sodium_Crypto::box_secretkey($boxKeypair),
689 ParagonIE_Sodium_Crypto::box_publickey($boxKeypair)
690 )
691 );
692 }
693
694
695 /**
696 * @param resource $ifp
697 * @param resource $ofp
698 * @param int $mlen
699 * @param string $nonce
700 * @param string $boxKeypair
701 * @return bool
702 * @throws SodiumException
703 * @throws TypeError
704 */
705 protected static function box_decrypt(
706 $ifp,
707 $ofp,
708 int $mlen,
709 string $nonce,
710 #[SensitiveParameter]
711 string $boxKeypair
712 ): bool {
713 return self::secretbox_decrypt(
714 $ifp,
715 $ofp,
716 $mlen,
717 $nonce,
718 ParagonIE_Sodium_Crypto::box_beforenm(
719 ParagonIE_Sodium_Crypto::box_secretkey($boxKeypair),
720 ParagonIE_Sodium_Crypto::box_publickey($boxKeypair)
721 )
722 );
723 }
724
725 /**
726 * Encrypt a file
727 *
728 * @param resource $ifp
729 * @param resource $ofp
730 * @param int $mlen
731 * @param string $nonce
732 * @param string $key
733 * @return bool
734 * @throws SodiumException
735 * @throws TypeError
736 */
737 protected static function secretbox_encrypt(
738 $ifp,
739 $ofp,
740 int $mlen,
741 string $nonce,
742 #[SensitiveParameter]
743 string $key
744 ): bool {
745 $plaintext = fread($ifp, 32);
746 if (!is_string($plaintext)) {
747 throw new SodiumException('Could not read input file');
748 }
749 $first32 = self::ftell($ifp);
750
751 $subkey = ParagonIE_Sodium_Core_HSalsa20::hsalsa20($nonce, $key);
752 $realNonce = ParagonIE_Sodium_Core_Util::substr($nonce, 16, 8);
753 $block0 = str_repeat("\x00", 32);
754
755 /* Length of the plaintext message */
756 $mlen0 = $mlen;
757 if ($mlen0 > 64 - ParagonIE_Sodium_Crypto::secretbox_xsalsa20poly1305_ZEROBYTES) {
758 $mlen0 = 64 - ParagonIE_Sodium_Crypto::secretbox_xsalsa20poly1305_ZEROBYTES;
759 }
760 $block0 .= ParagonIE_Sodium_Core_Util::substr($plaintext, 0, $mlen0);
761
762 /** @var string $block0 */
763 $block0 = ParagonIE_Sodium_Core_Salsa20::salsa20_xor(
764 $block0,
765 $realNonce,
766 $subkey
767 );
768
769 $state = new ParagonIE_Sodium_Core_Poly1305_State(
770 ParagonIE_Sodium_Core_Util::substr(
771 $block0,
772 0,
773 ParagonIE_Sodium_Crypto::onetimeauth_poly1305_KEYBYTES
774 )
775 );
776
777 // Pre-write 16 blank bytes for the Poly1305 tag
778 $start = self::ftell($ofp);
779 fwrite($ofp, str_repeat("\x00", 16));
780
781 /** @var string $c */
782 $cBlock = ParagonIE_Sodium_Core_Util::substr(
783 $block0,
784 ParagonIE_Sodium_Crypto::secretbox_xsalsa20poly1305_ZEROBYTES
785 );
786 $state->update($cBlock);
787 fwrite($ofp, $cBlock);
788 $mlen -= 32;
789
790 $iter = 1;
791 $incr = self::BUFFER_SIZE >> 6;
792 /*
793 * Set the cursor to the end of the first half-block. All future bytes will
794 * generated from salsa20_xor_ic, starting from 1 (second block).
795 */
796 fseek($ifp, $first32);
797
798 while ($mlen > 0) {
799 $blockSize = min($mlen, self::BUFFER_SIZE);
800 $plaintext = fread($ifp, $blockSize);
801 if (!is_string($plaintext)) {
802 throw new SodiumException('Could not read input file');
803 }
804 $cBlock = ParagonIE_Sodium_Core_Salsa20::salsa20_xor_ic(
805 $plaintext,
806 $realNonce,
807 $iter,
808 $subkey
809 );
810 fwrite($ofp, $cBlock, $blockSize);
811 $state->update($cBlock);
812
813 $mlen -= $blockSize;
814 $iter += $incr;
815 }
816 try {
817 ParagonIE_Sodium_Compat::memzero($block0);
818 ParagonIE_Sodium_Compat::memzero($subkey);
819 } catch (SodiumException) {
820 $block0 = null;
821 $subkey = null;
822 }
823 $end = self::ftell($ofp);
824
825 /*
826 * Write the Poly1305 authentication tag that provides integrity
827 * over the ciphertext (encrypt-then-MAC)
828 */
829 fseek($ofp, $start);
830 fwrite($ofp, $state->finish(), ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_MACBYTES);
831 fseek($ofp, $end);
832 unset($state);
833
834 return true;
835 }
836
837 /**
838 * Decrypt a file
839 *
840 * @param resource $ifp
841 * @param resource $ofp
842 * @param int $mlen
843 * @param string $nonce
844 * @param string $key
845 * @return bool
846 * @throws SodiumException
847 * @throws TypeError
848 */
849 protected static function secretbox_decrypt(
850 $ifp,
851 $ofp,
852 int $mlen,
853 string $nonce,
854 #[SensitiveParameter]
855 string $key
856 ): bool {
857 $tag = fread($ifp, 16);
858 if (!is_string($tag)) {
859 throw new SodiumException('Could not read input file');
860 }
861
862 $subkey = ParagonIE_Sodium_Core_HSalsa20::hsalsa20($nonce, $key);
863 $realNonce = ParagonIE_Sodium_Core_Util::substr($nonce, 16, 8);
864 $block0 = ParagonIE_Sodium_Core_Salsa20::salsa20(
865 64,
866 ParagonIE_Sodium_Core_Util::substr($nonce, 16, 8),
867 $subkey
868 );
869
870 /* Verify the Poly1305 MAC -before- attempting to decrypt! */
871 $state = new ParagonIE_Sodium_Core_Poly1305_State(self::substr($block0, 0, 32));
872 if (!self::onetimeauth_verify($state, $ifp, $tag, $mlen)) {
873 throw new SodiumException('Invalid MAC');
874 }
875
876 /*
877 * Set the cursor to the end of the first half-block. All future bytes will
878 * generated from salsa20_xor_ic, starting from 1 (second block).
879 */
880 $first32 = fread($ifp, 32);
881 if (!is_string($first32)) {
882 throw new SodiumException('Could not read input file');
883 }
884 $first32len = self::strlen($first32);
885 fwrite(
886 $ofp,
887 self::xorStrings(
888 self::substr($block0, 32, $first32len),
889 self::substr($first32, 0, $first32len)
890 )
891 );
892 $mlen -= 32;
893 $iter = 1;
894 $incr = self::BUFFER_SIZE >> 6;
895
896 /* Decrypts ciphertext, writes to output file. */
897 while ($mlen > 0) {
898 $blockSize = min($mlen, self::BUFFER_SIZE);
899 $ciphertext = fread($ifp, $blockSize);
900 if (!is_string($ciphertext)) {
901 throw new SodiumException('Could not read input file');
902 }
903 $pBlock = ParagonIE_Sodium_Core_Salsa20::salsa20_xor_ic(
904 $ciphertext,
905 $realNonce,
906 $iter,
907 $subkey
908 );
909 fwrite($ofp, $pBlock, $blockSize);
910 $mlen -= $blockSize;
911 $iter += $incr;
912 }
913 return true;
914 }
915
916 /**
917 * @param ParagonIE_Sodium_Core_Poly1305_State $state
918 * @param resource $ifp
919 * @param string $tag
920 * @param int $mlen
921 * @return bool
922 * @throws SodiumException
923 * @throws TypeError
924 */
925 protected static function onetimeauth_verify(
926 ParagonIE_Sodium_Core_Poly1305_State $state,
927 $ifp,
928 string $tag = '',
929 int $mlen = 0
930 ): bool {
931 $pos = self::ftell($ifp);
932 while ($mlen > 0) {
933 $blockSize = min($mlen, self::BUFFER_SIZE);
934 $ciphertext = fread($ifp, $blockSize);
935 if (!is_string($ciphertext)) {
936 throw new SodiumException('Could not read input file');
937 }
938 $state->update($ciphertext);
939 $mlen -= $blockSize;
940 }
941 $res = ParagonIE_Sodium_Core_Util::verify_16($tag, $state->finish());
942
943 fseek($ifp, $pos);
944 return $res;
945 }
946
947 /**
948 * Update a hash context with the contents of a file, without
949 * loading the entire file into memory.
950 *
951 * @param HashContext $hash
952 * @param resource $fp
953 * @param int $size
954 * @return HashContext Resource on PHP < 7.2, HashContext object on PHP >= 7.2
955 * @throws SodiumException
956 * @throws TypeError
957 */
958 public static function updateHashWithFile(HashContext $hash, $fp, int $size = 0): HashContext
959 {
960 /**
961 * @psalm-suppress DocblockTypeContradiction
962 * We can't statically type resources.
963 */
964 if (!is_resource($fp)) {
965 throw new TypeError('Argument 2 must be a resource, ' . gettype($fp) . ' given.');
966 }
967 $originalPosition = self::ftell($fp);
968
969 // Move file pointer to beginning of file
970 fseek($fp, 0);
971 for ($i = 0; $i < $size; $i += self::BUFFER_SIZE) {
972 /** @var string|bool $message */
973 $message = fread(
974 $fp,
975 ($size - $i) > self::BUFFER_SIZE
976 ? $size - $i
977 : self::BUFFER_SIZE
978 );
979 if (!is_string($message)) {
980 throw new SodiumException('Unexpected error reading from file.');
981 }
982 hash_update($hash, $message);
983 }
984 // Reset file pointer's position
985 fseek($fp, $originalPosition);
986 return $hash;
987 }
988
989 /**
990 * @param resource $resource
991 * @return int
992 * @throws SodiumException
993 */
994 private static function ftell($resource): int
995 {
996 $return = ftell($resource);
997 if (!is_int($return)) {
998 throw new SodiumException('ftell() returned false');
999 }
1000 return $return;
1001 }
1002 }