[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/sodium_compat/src/ -> File.php (source)

   1  <?php
   2  
   3  if (class_exists('ParagonIE_Sodium_File', false)) {
   4      return;
   5  }
   6  /**
   7   * Class ParagonIE_Sodium_File
   8   */
   9  class ParagonIE_Sodium_File extends ParagonIE_Sodium_Core_Util
  10  {
  11      /* PHP's default buffer size is 8192 for fread()/fwrite(). */
  12      const BUFFER_SIZE = 8192;
  13  
  14      /**
  15       * Box a file (rather than a string). Uses less memory than
  16       * ParagonIE_Sodium_Compat::crypto_box(), but produces
  17       * the same result.
  18       *
  19       * @param string $inputFile  Absolute path to a file on the filesystem
  20       * @param string $outputFile Absolute path to a file on the filesystem
  21       * @param string $nonce      Number to be used only once
  22       * @param string $keyPair    ECDH secret key and ECDH public key concatenated
  23       *
  24       * @return bool
  25       * @throws SodiumException
  26       * @throws TypeError
  27       */
  28      public static function box(
  29          $inputFile,
  30          $outputFile,
  31          $nonce,
  32          #[\SensitiveParameter]
  33          $keyPair
  34      ) {
  35          /* Type checks: */
  36          if (!is_string($inputFile)) {
  37              throw new TypeError('Argument 1 must be a string, ' . gettype($inputFile) . ' given.');
  38          }
  39          if (!is_string($outputFile)) {
  40              throw new TypeError('Argument 2 must be a string, ' . gettype($outputFile) . ' given.');
  41          }
  42          if (!is_string($nonce)) {
  43              throw new TypeError('Argument 3 must be a string, ' . gettype($nonce) . ' given.');
  44          }
  45  
  46          /* Input validation: */
  47          if (!is_string($keyPair)) {
  48              throw new TypeError('Argument 4 must be a string, ' . gettype($keyPair) . ' given.');
  49          }
  50          if (self::strlen($nonce) !== ParagonIE_Sodium_Compat::CRYPTO_BOX_NONCEBYTES) {
  51              throw new TypeError('Argument 3 must be CRYPTO_BOX_NONCEBYTES bytes');
  52          }
  53          if (self::strlen($keyPair) !== ParagonIE_Sodium_Compat::CRYPTO_BOX_KEYPAIRBYTES) {
  54              throw new TypeError('Argument 4 must be CRYPTO_BOX_KEYPAIRBYTES bytes');
  55          }
  56  
  57          /** @var int $size */
  58          $size = filesize($inputFile);
  59          if (!is_int($size)) {
  60              throw new SodiumException('Could not obtain the file size');
  61          }
  62  
  63          /** @var resource $ifp */
  64          $ifp = fopen($inputFile, 'rb');
  65          if (!is_resource($ifp)) {
  66              throw new SodiumException('Could not open input file for reading');
  67          }
  68  
  69          /** @var resource $ofp */
  70          $ofp = fopen($outputFile, 'wb');
  71          if (!is_resource($ofp)) {
  72              fclose($ifp);
  73              throw new SodiumException('Could not open output file for writing');
  74          }
  75  
  76          $res = self::box_encrypt($ifp, $ofp, $size, $nonce, $keyPair);
  77          fclose($ifp);
  78          fclose($ofp);
  79          return $res;
  80      }
  81  
  82      /**
  83       * Open a boxed file (rather than a string). Uses less memory than
  84       * ParagonIE_Sodium_Compat::crypto_box_open(), but produces
  85       * the same result.
  86       *
  87       * Warning: Does not protect against TOCTOU attacks. You should
  88       * just load the file into memory and use crypto_box_open() if
  89       * you are worried about those.
  90       *
  91       * @param string $inputFile
  92       * @param string $outputFile
  93       * @param string $nonce
  94       * @param string $keypair
  95       * @return bool
  96       * @throws SodiumException
  97       * @throws TypeError
  98       */
  99      public static function box_open(
 100          $inputFile,
 101          $outputFile,
 102          $nonce,
 103          #[\SensitiveParameter]
 104          $keypair
 105      ) {
 106          /* Type checks: */
 107          if (!is_string($inputFile)) {
 108              throw new TypeError('Argument 1 must be a string, ' . gettype($inputFile) . ' given.');
 109          }
 110          if (!is_string($outputFile)) {
 111              throw new TypeError('Argument 2 must be a string, ' . gettype($outputFile) . ' given.');
 112          }
 113          if (!is_string($nonce)) {
 114              throw new TypeError('Argument 3 must be a string, ' . gettype($nonce) . ' given.');
 115          }
 116          if (!is_string($keypair)) {
 117              throw new TypeError('Argument 4 must be a string, ' . gettype($keypair) . ' given.');
 118          }
 119  
 120          /* Input validation: */
 121          if (self::strlen($nonce) !== ParagonIE_Sodium_Compat::CRYPTO_BOX_NONCEBYTES) {
 122              throw new TypeError('Argument 4 must be CRYPTO_BOX_NONCEBYTES bytes');
 123          }
 124          if (self::strlen($keypair) !== ParagonIE_Sodium_Compat::CRYPTO_BOX_KEYPAIRBYTES) {
 125              throw new TypeError('Argument 4 must be CRYPTO_BOX_KEYPAIRBYTES bytes');
 126          }
 127  
 128          if (!file_exists($inputFile)) {
 129              throw new SodiumException('Input file does not exist');
 130          }
 131          /** @var int $size */
 132          $size = filesize($inputFile);
 133          if (!is_int($size)) {
 134              throw new SodiumException('Could not obtain the file size');
 135          }
 136  
 137          /** @var resource $ifp */
 138          $ifp = fopen($inputFile, 'rb');
 139          if (!is_resource($ifp)) {
 140              throw new SodiumException('Could not open input file for reading');
 141          }
 142  
 143          /** @var resource $destination */
 144          $destination = self::openOutputFile($outputFile);
 145          if (!is_resource($destination)) {
 146              fclose($ifp);
 147              throw new SodiumException('Could not open output file for writing');
 148          }
 149          /** @var resource $ofp */
 150          $ofp = tmpfile();
 151          if (!is_resource($ofp)) {
 152              fclose($ifp);
 153              fclose($destination);
 154              throw new SodiumException('Could not open temporary output file for writing');
 155          }
 156  
 157          try {
 158              $res = self::box_decrypt($ifp, $ofp, $size, $nonce, $keypair);
 159              self::commitAuthenticatedOutput($ofp, $destination);
 160          } catch (Exception $ex) {
 161              fclose($ifp);
 162              fclose($ofp);
 163              fclose($destination);
 164              throw $ex;
 165          }
 166          fclose($ifp);
 167          fclose($ofp);
 168          fclose($destination);
 169          try {
 170              ParagonIE_Sodium_Compat::memzero($nonce);
 171              ParagonIE_Sodium_Compat::memzero($ephKeypair);
 172          } catch (SodiumException $ex) {
 173              if (isset($ephKeypair)) {
 174                  unset($ephKeypair);
 175              }
 176          }
 177          return $res;
 178      }
 179  
 180      /**
 181       * Seal a file (rather than a string). Uses less memory than
 182       * ParagonIE_Sodium_Compat::crypto_box_seal(), but produces
 183       * the same result.
 184       *
 185       * @param string $inputFile  Absolute path to a file on the filesystem
 186       * @param string $outputFile Absolute path to a file on the filesystem
 187       * @param string $publicKey  ECDH public key
 188       *
 189       * @return bool
 190       * @throws SodiumException
 191       * @throws TypeError
 192       */
 193      public static function box_seal(
 194          $inputFile,
 195          $outputFile,
 196          #[\SensitiveParameter]
 197          $publicKey
 198      ) {
 199          /* Type checks: */
 200          if (!is_string($inputFile)) {
 201              throw new TypeError('Argument 1 must be a string, ' . gettype($inputFile) . ' given.');
 202          }
 203          if (!is_string($outputFile)) {
 204              throw new TypeError('Argument 2 must be a string, ' . gettype($outputFile) . ' given.');
 205          }
 206          if (!is_string($publicKey)) {
 207              throw new TypeError('Argument 3 must be a string, ' . gettype($publicKey) . ' given.');
 208          }
 209  
 210          /* Input validation: */
 211          if (self::strlen($publicKey) !== ParagonIE_Sodium_Compat::CRYPTO_BOX_PUBLICKEYBYTES) {
 212              throw new TypeError('Argument 3 must be CRYPTO_BOX_PUBLICKEYBYTES bytes');
 213          }
 214  
 215          if (!file_exists($inputFile)) {
 216              throw new SodiumException('Input file does not exist');
 217          }
 218          /** @var int $size */
 219          $size = filesize($inputFile);
 220          if (!is_int($size)) {
 221              throw new SodiumException('Could not obtain the file size');
 222          }
 223  
 224          /** @var resource $ifp */
 225          $ifp = fopen($inputFile, 'rb');
 226          if (!is_resource($ifp)) {
 227              throw new SodiumException('Could not open input file for reading');
 228          }
 229  
 230          /** @var resource $ofp */
 231          $ofp = @fopen($outputFile, 'wb');
 232          if (!is_resource($ofp)) {
 233              fclose($ifp);
 234              throw new SodiumException('Could not open output file for writing');
 235          }
 236  
 237          /** @var string $ephKeypair */
 238          $ephKeypair = ParagonIE_Sodium_Compat::crypto_box_keypair();
 239  
 240          /** @var string $msgKeypair */
 241          $msgKeypair = ParagonIE_Sodium_Compat::crypto_box_keypair_from_secretkey_and_publickey(
 242              ParagonIE_Sodium_Compat::crypto_box_secretkey($ephKeypair),
 243              $publicKey
 244          );
 245  
 246          /** @var string $ephemeralPK */
 247          $ephemeralPK = ParagonIE_Sodium_Compat::crypto_box_publickey($ephKeypair);
 248  
 249          /** @var string $nonce */
 250          $nonce = ParagonIE_Sodium_Compat::crypto_generichash(
 251              $ephemeralPK . $publicKey,
 252              '',
 253              24
 254          );
 255  
 256          /** @var int $firstWrite */
 257          $firstWrite = fwrite(
 258              $ofp,
 259              $ephemeralPK,
 260              ParagonIE_Sodium_Compat::CRYPTO_BOX_PUBLICKEYBYTES
 261          );
 262          if (!is_int($firstWrite)) {
 263              fclose($ifp);
 264              fclose($ofp);
 265              ParagonIE_Sodium_Compat::memzero($ephKeypair);
 266              throw new SodiumException('Could not write to output file');
 267          }
 268          if ($firstWrite !== ParagonIE_Sodium_Compat::CRYPTO_BOX_PUBLICKEYBYTES) {
 269              ParagonIE_Sodium_Compat::memzero($ephKeypair);
 270              fclose($ifp);
 271              fclose($ofp);
 272              throw new SodiumException('Error writing public key to output file');
 273          }
 274  
 275          $res = self::box_encrypt($ifp, $ofp, $size, $nonce, $msgKeypair);
 276          fclose($ifp);
 277          fclose($ofp);
 278          try {
 279              ParagonIE_Sodium_Compat::memzero($nonce);
 280              ParagonIE_Sodium_Compat::memzero($ephKeypair);
 281          } catch (SodiumException $ex) {
 282              /** @psalm-suppress PossiblyUndefinedVariable */
 283              unset($ephKeypair);
 284          }
 285          return $res;
 286      }
 287  
 288      /**
 289       * Open a sealed file (rather than a string). Uses less memory than
 290       * ParagonIE_Sodium_Compat::crypto_box_seal_open(), but produces
 291       * the same result.
 292       *
 293       * Warning: Does not protect against TOCTOU attacks. You should
 294       * just load the file into memory and use crypto_box_seal_open() if
 295       * you are worried about those.
 296       *
 297       * @param string $inputFile
 298       * @param string $outputFile
 299       * @param string $ecdhKeypair
 300       * @return bool
 301       * @throws SodiumException
 302       * @throws TypeError
 303       */
 304      public static function box_seal_open(
 305          $inputFile,
 306          $outputFile,
 307          #[\SensitiveParameter]
 308          $ecdhKeypair
 309      ) {
 310          /* Type checks: */
 311          if (!is_string($inputFile)) {
 312              throw new TypeError('Argument 1 must be a string, ' . gettype($inputFile) . ' given.');
 313          }
 314          if (!is_string($outputFile)) {
 315              throw new TypeError('Argument 2 must be a string, ' . gettype($outputFile) . ' given.');
 316          }
 317          if (!is_string($ecdhKeypair)) {
 318              throw new TypeError('Argument 3 must be a string, ' . gettype($ecdhKeypair) . ' given.');
 319          }
 320  
 321          /* Input validation: */
 322          if (self::strlen($ecdhKeypair) !== ParagonIE_Sodium_Compat::CRYPTO_BOX_KEYPAIRBYTES) {
 323              throw new TypeError('Argument 3 must be CRYPTO_BOX_KEYPAIRBYTES bytes');
 324          }
 325  
 326          $publicKey = ParagonIE_Sodium_Compat::crypto_box_publickey($ecdhKeypair);
 327  
 328          if (!file_exists($inputFile)) {
 329              throw new SodiumException('Input file does not exist');
 330          }
 331          /** @var int $size */
 332          $size = filesize($inputFile);
 333          if (!is_int($size)) {
 334              throw new SodiumException('Could not obtain the file size');
 335          }
 336  
 337          /** @var resource $ifp */
 338          $ifp = fopen($inputFile, 'rb');
 339          if (!is_resource($ifp)) {
 340              throw new SodiumException('Could not open input file for reading');
 341          }
 342  
 343          $ephemeralPK = fread($ifp, ParagonIE_Sodium_Compat::CRYPTO_BOX_PUBLICKEYBYTES);
 344          if (!is_string($ephemeralPK)) {
 345              fclose($ifp);
 346              throw new SodiumException('Could not read input file');
 347          }
 348          if (self::strlen($ephemeralPK) !== ParagonIE_Sodium_Compat::CRYPTO_BOX_PUBLICKEYBYTES) {
 349              fclose($ifp);
 350              throw new SodiumException('Could not read public key from sealed file');
 351          }
 352  
 353          $nonce = ParagonIE_Sodium_Compat::crypto_generichash(
 354              $ephemeralPK . $publicKey,
 355              '',
 356              24
 357          );
 358          $msgKeypair = ParagonIE_Sodium_Compat::crypto_box_keypair_from_secretkey_and_publickey(
 359              ParagonIE_Sodium_Compat::crypto_box_secretkey($ecdhKeypair),
 360              $ephemeralPK
 361          );
 362  
 363          /** @var resource $destination */
 364          $destination = self::openOutputFile($outputFile);
 365          if (!is_resource($destination)) {
 366              fclose($ifp);
 367              throw new SodiumException('Could not open output file for writing');
 368          }
 369          /** @var resource $ofp */
 370          $ofp = tmpfile();
 371          if (!is_resource($ofp)) {
 372              fclose($ifp);
 373              fclose($destination);
 374              throw new SodiumException('Could not open temporary output file for writing');
 375          }
 376  
 377          try {
 378              $res = self::box_decrypt($ifp, $ofp, $size, $nonce, $msgKeypair);
 379              self::commitAuthenticatedOutput($ofp, $destination);
 380          } catch (Exception $ex) {
 381              fclose($ifp);
 382              fclose($ofp);
 383              fclose($destination);
 384              throw $ex;
 385          }
 386          fclose($ifp);
 387          fclose($ofp);
 388          fclose($destination);
 389          try {
 390              ParagonIE_Sodium_Compat::memzero($nonce);
 391              ParagonIE_Sodium_Compat::memzero($ephKeypair);
 392          } catch (SodiumException $ex) {
 393              if (isset($ephKeypair)) {
 394                  unset($ephKeypair);
 395              }
 396          }
 397          return $res;
 398      }
 399  
 400      /**
 401       * Calculate the BLAKE2b hash of a file.
 402       *
 403       * @param string      $filePath     Absolute path to a file on the filesystem
 404       * @param string|null $key          BLAKE2b key
 405       * @param int         $outputLength Length of hash output
 406       *
 407       * @return string                   BLAKE2b hash
 408       * @throws SodiumException
 409       * @throws TypeError
 410       * @psalm-suppress FailedTypeResolution
 411       */
 412      public static function generichash(
 413          $filePath,
 414          #[\SensitiveParameter]
 415          $key = '',
 416          $outputLength = 32
 417      ) {
 418          /* Type checks: */
 419          if (!is_string($filePath)) {
 420              throw new TypeError('Argument 1 must be a string, ' . gettype($filePath) . ' given.');
 421          }
 422          if (!is_string($key)) {
 423              if (is_null($key)) {
 424                  $key = '';
 425              } else {
 426                  throw new TypeError('Argument 2 must be a string, ' . gettype($key) . ' given.');
 427              }
 428          }
 429          if (!is_int($outputLength)) {
 430              if (!is_numeric($outputLength)) {
 431                  throw new TypeError('Argument 3 must be an integer, ' . gettype($outputLength) . ' given.');
 432              }
 433              $outputLength = (int) $outputLength;
 434          }
 435  
 436          /* Input validation: */
 437          if (!empty($key)) {
 438              if (self::strlen($key) < ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_KEYBYTES_MIN) {
 439                  throw new TypeError('Argument 2 must be at least CRYPTO_GENERICHASH_KEYBYTES_MIN bytes');
 440              }
 441              if (self::strlen($key) > ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_KEYBYTES_MAX) {
 442                  throw new TypeError('Argument 2 must be at most CRYPTO_GENERICHASH_KEYBYTES_MAX bytes');
 443              }
 444          }
 445          if ($outputLength < ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_BYTES_MIN) {
 446              throw new SodiumException('Argument 3 must be at least CRYPTO_GENERICHASH_BYTES_MIN');
 447          }
 448          if ($outputLength > ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_BYTES_MAX) {
 449              throw new SodiumException('Argument 3 must be at least CRYPTO_GENERICHASH_BYTES_MAX');
 450          }
 451  
 452          if (!file_exists($filePath)) {
 453              throw new SodiumException('File does not exist');
 454          }
 455          /** @var int $size */
 456          $size = filesize($filePath);
 457          if (!is_int($size)) {
 458              throw new SodiumException('Could not obtain the file size');
 459          }
 460  
 461          /** @var resource $fp */
 462          $fp = fopen($filePath, 'rb');
 463          if (!is_resource($fp)) {
 464              throw new SodiumException('Could not open input file for reading');
 465          }
 466          $ctx = ParagonIE_Sodium_Compat::crypto_generichash_init($key, $outputLength);
 467          while ($size > 0) {
 468              $blockSize = $size > 64
 469                  ? 64
 470                  : $size;
 471              $read = fread($fp, $blockSize);
 472              if (!is_string($read)) {
 473                  throw new SodiumException('Could not read input file');
 474              }
 475              ParagonIE_Sodium_Compat::crypto_generichash_update($ctx, $read);
 476              $size -= $blockSize;
 477          }
 478  
 479          fclose($fp);
 480          return ParagonIE_Sodium_Compat::crypto_generichash_final($ctx, $outputLength);
 481      }
 482  
 483      /**
 484       * Encrypt a file (rather than a string). Uses less memory than
 485       * ParagonIE_Sodium_Compat::crypto_secretbox(), but produces
 486       * the same result.
 487       *
 488       * @param string $inputFile  Absolute path to a file on the filesystem
 489       * @param string $outputFile Absolute path to a file on the filesystem
 490       * @param string $nonce      Number to be used only once
 491       * @param string $key        Encryption key
 492       *
 493       * @return bool
 494       * @throws SodiumException
 495       * @throws TypeError
 496       */
 497      public static function secretbox(
 498          $inputFile,
 499          $outputFile,
 500          $nonce,
 501          #[\SensitiveParameter]
 502          $key
 503      ) {
 504          /* Type checks: */
 505          if (!is_string($inputFile)) {
 506              throw new TypeError('Argument 1 must be a string, ' . gettype($inputFile) . ' given..');
 507          }
 508          if (!is_string($outputFile)) {
 509              throw new TypeError('Argument 2 must be a string, ' . gettype($outputFile) . ' given.');
 510          }
 511          if (!is_string($nonce)) {
 512              throw new TypeError('Argument 3 must be a string, ' . gettype($nonce) . ' given.');
 513          }
 514  
 515          /* Input validation: */
 516          if (self::strlen($nonce) !== ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_NONCEBYTES) {
 517              throw new TypeError('Argument 3 must be CRYPTO_SECRETBOX_NONCEBYTES bytes');
 518          }
 519          if (!is_string($key)) {
 520              throw new TypeError('Argument 4 must be a string, ' . gettype($key) . ' given.');
 521          }
 522          if (self::strlen($key) !== ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_KEYBYTES) {
 523              throw new TypeError('Argument 4 must be CRYPTO_SECRETBOX_KEYBYTES bytes');
 524          }
 525  
 526          if (!file_exists($inputFile)) {
 527              throw new SodiumException('Input file does not exist');
 528          }
 529          /** @var int $size */
 530          $size = filesize($inputFile);
 531          if (!is_int($size)) {
 532              throw new SodiumException('Could not obtain the file size');
 533          }
 534  
 535          /** @var resource $ifp */
 536          $ifp = @fopen($inputFile, 'rb');
 537          if (!is_resource($ifp)) {
 538              throw new SodiumException('Could not open input file for reading');
 539          }
 540  
 541          /** @var resource $ofp */
 542          $ofp = fopen($outputFile, 'wb');
 543          if (!is_resource($ofp)) {
 544              fclose($ifp);
 545              throw new SodiumException('Could not open output file for writing');
 546          }
 547  
 548          $res = self::secretbox_encrypt($ifp, $ofp, $size, $nonce, $key);
 549          fclose($ifp);
 550          fclose($ofp);
 551          return $res;
 552      }
 553      /**
 554       * Seal a file (rather than a string). Uses less memory than
 555       * ParagonIE_Sodium_Compat::crypto_secretbox_open(), but produces
 556       * the same result.
 557       *
 558       * Warning: Does not protect against TOCTOU attacks. You should
 559       * just load the file into memory and use crypto_secretbox_open() if
 560       * you are worried about those.
 561       *
 562       * @param string $inputFile
 563       * @param string $outputFile
 564       * @param string $nonce
 565       * @param string $key
 566       * @return bool
 567       * @throws SodiumException
 568       * @throws TypeError
 569       */
 570      public static function secretbox_open(
 571          $inputFile,
 572          $outputFile,
 573          $nonce,
 574          #[\SensitiveParameter]
 575          $key
 576      ) {
 577          /* Type checks: */
 578          if (!is_string($inputFile)) {
 579              throw new TypeError('Argument 1 must be a string, ' . gettype($inputFile) . ' given.');
 580          }
 581          if (!is_string($outputFile)) {
 582              throw new TypeError('Argument 2 must be a string, ' . gettype($outputFile) . ' given.');
 583          }
 584          if (!is_string($nonce)) {
 585              throw new TypeError('Argument 3 must be a string, ' . gettype($nonce) . ' given.');
 586          }
 587          if (!is_string($key)) {
 588              throw new TypeError('Argument 4 must be a string, ' . gettype($key) . ' given.');
 589          }
 590  
 591          /* Input validation: */
 592          if (self::strlen($nonce) !== ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_NONCEBYTES) {
 593              throw new TypeError('Argument 3 must be CRYPTO_SECRETBOX_NONCEBYTES bytes');
 594          }
 595          if (self::strlen($key) !== ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_KEYBYTES) {
 596              throw new TypeError('Argument 4 must be CRYPTO_SECRETBOX_KEYBYTES bytes');
 597          }
 598  
 599          if (!file_exists($inputFile)) {
 600              throw new SodiumException('Input file does not exist');
 601          }
 602          /** @var int $size */
 603          $size = filesize($inputFile);
 604          if (!is_int($size)) {
 605              throw new SodiumException('Could not obtain the file size');
 606          }
 607  
 608          /** @var resource $ifp */
 609          $ifp = fopen($inputFile, 'rb');
 610          if (!is_resource($ifp)) {
 611              throw new SodiumException('Could not open input file for reading');
 612          }
 613  
 614          /** @var resource $destination */
 615          $destination = self::openOutputFile($outputFile);
 616          if (!is_resource($destination)) {
 617              fclose($ifp);
 618              throw new SodiumException('Could not open output file for writing');
 619          }
 620          /** @var resource $ofp */
 621          $ofp = tmpfile();
 622          if (!is_resource($ofp)) {
 623              fclose($ifp);
 624              fclose($destination);
 625              throw new SodiumException('Could not open temporary output file for writing');
 626          }
 627  
 628          try {
 629              $res = self::secretbox_decrypt($ifp, $ofp, $size, $nonce, $key);
 630              self::commitAuthenticatedOutput($ofp, $destination);
 631          } catch (Exception $ex) {
 632              fclose($ifp);
 633              fclose($ofp);
 634              fclose($destination);
 635              throw $ex;
 636          }
 637          fclose($ifp);
 638          fclose($ofp);
 639          fclose($destination);
 640          try {
 641              ParagonIE_Sodium_Compat::memzero($key);
 642          } catch (SodiumException $ex) {
 643              /** @psalm-suppress PossiblyUndefinedVariable */
 644              unset($key);
 645          }
 646          return $res;
 647      }
 648  
 649      /**
 650       * Sign a file (rather than a string). Uses less memory than
 651       * ParagonIE_Sodium_Compat::crypto_sign_detached(), but produces
 652       * the same result.
 653       *
 654       * @param string $filePath  Absolute path to a file on the filesystem
 655       * @param string $secretKey Secret signing key
 656       *
 657       * @return string           Ed25519 signature
 658       * @throws SodiumException
 659       * @throws TypeError
 660       */
 661      public static function sign(
 662          $filePath,
 663          #[\SensitiveParameter]
 664          $secretKey
 665      ) {
 666          /* Type checks: */
 667          if (!is_string($filePath)) {
 668              throw new TypeError('Argument 1 must be a string, ' . gettype($filePath) . ' given.');
 669          }
 670          if (!is_string($secretKey)) {
 671              throw new TypeError('Argument 2 must be a string, ' . gettype($secretKey) . ' given.');
 672          }
 673  
 674          /* Input validation: */
 675          if (self::strlen($secretKey) !== ParagonIE_Sodium_Compat::CRYPTO_SIGN_SECRETKEYBYTES) {
 676              throw new TypeError('Argument 2 must be CRYPTO_SIGN_SECRETKEYBYTES bytes');
 677          }
 678          if (PHP_INT_SIZE === 4) {
 679              return self::sign_core32($filePath, $secretKey);
 680          }
 681  
 682          if (!file_exists($filePath)) {
 683              throw new SodiumException('File does not exist');
 684          }
 685          /** @var int $size */
 686          $size = filesize($filePath);
 687          if (!is_int($size)) {
 688              throw new SodiumException('Could not obtain the file size');
 689          }
 690  
 691          /** @var resource $fp */
 692          $fp = fopen($filePath, 'rb');
 693          if (!is_resource($fp)) {
 694              throw new SodiumException('Could not open input file for reading');
 695          }
 696  
 697          /** @var string $az */
 698          $az = hash('sha512', self::substr($secretKey, 0, 32), true);
 699  
 700          $az[0] = self::intToChr(self::chrToInt($az[0]) & 248);
 701          $az[31] = self::intToChr((self::chrToInt($az[31]) & 63) | 64);
 702  
 703          $hs = hash_init('sha512');
 704          self::hash_update($hs, self::substr($az, 32, 32));
 705          /** @var resource $hs */
 706          $hs = self::updateHashWithFile($hs, $fp, $size);
 707  
 708          /** @var string $nonceHash */
 709          $nonceHash = hash_final($hs, true);
 710  
 711          /** @var string $pk */
 712          $pk = self::substr($secretKey, 32, 32);
 713  
 714          /** @var string $nonce */
 715          $nonce = ParagonIE_Sodium_Core_Ed25519::sc_reduce($nonceHash) . self::substr($nonceHash, 32);
 716  
 717          /** @var string $sig */
 718          $sig = ParagonIE_Sodium_Core_Ed25519::ge_p3_tobytes(
 719              ParagonIE_Sodium_Core_Ed25519::ge_scalarmult_base($nonce)
 720          );
 721  
 722          $hs = hash_init('sha512');
 723          self::hash_update($hs, self::substr($sig, 0, 32));
 724          self::hash_update($hs, self::substr($pk, 0, 32));
 725          /** @var resource $hs */
 726          $hs = self::updateHashWithFile($hs, $fp, $size);
 727  
 728          /** @var string $hramHash */
 729          $hramHash = hash_final($hs, true);
 730  
 731          /** @var string $hram */
 732          $hram = ParagonIE_Sodium_Core_Ed25519::sc_reduce($hramHash);
 733  
 734          /** @var string $sigAfter */
 735          $sigAfter = ParagonIE_Sodium_Core_Ed25519::sc_muladd($hram, $az, $nonce);
 736  
 737          /** @var string $sig */
 738          $sig = self::substr($sig, 0, 32) . self::substr($sigAfter, 0, 32);
 739  
 740          try {
 741              ParagonIE_Sodium_Compat::memzero($az);
 742          } catch (SodiumException $ex) {
 743              $az = null;
 744          }
 745          fclose($fp);
 746          return $sig;
 747      }
 748  
 749      /**
 750       * Verify a file (rather than a string). Uses less memory than
 751       * ParagonIE_Sodium_Compat::crypto_sign_verify_detached(), but
 752       * produces the same result.
 753       *
 754       * @param string $sig       Ed25519 signature
 755       * @param string $filePath  Absolute path to a file on the filesystem
 756       * @param string $publicKey Signing public key
 757       *
 758       * @return bool
 759       * @throws SodiumException
 760       * @throws TypeError
 761       * @throws Exception
 762       */
 763      public static function verify(
 764          $sig,
 765          $filePath,
 766          $publicKey
 767      ) {
 768          /* Type checks: */
 769          if (!is_string($sig)) {
 770              throw new TypeError('Argument 1 must be a string, ' . gettype($sig) . ' given.');
 771          }
 772          if (!is_string($filePath)) {
 773              throw new TypeError('Argument 2 must be a string, ' . gettype($filePath) . ' given.');
 774          }
 775          if (!is_string($publicKey)) {
 776              throw new TypeError('Argument 3 must be a string, ' . gettype($publicKey) . ' given.');
 777          }
 778  
 779          /* Input validation: */
 780          if (self::strlen($sig) !== ParagonIE_Sodium_Compat::CRYPTO_SIGN_BYTES) {
 781              throw new TypeError('Argument 1 must be CRYPTO_SIGN_BYTES bytes');
 782          }
 783          if (self::strlen($publicKey) !== ParagonIE_Sodium_Compat::CRYPTO_SIGN_PUBLICKEYBYTES) {
 784              throw new TypeError('Argument 3 must be CRYPTO_SIGN_PUBLICKEYBYTES bytes');
 785          }
 786          if (self::strlen($sig) < 64) {
 787              throw new SodiumException('Signature is too short');
 788          }
 789  
 790          if (PHP_INT_SIZE === 4) {
 791              return self::verify_core32($sig, $filePath, $publicKey);
 792          }
 793  
 794          /* Security checks */
 795          if (
 796              (ParagonIE_Sodium_Core_Ed25519::chrToInt($sig[63]) & 240)
 797                  &&
 798              ParagonIE_Sodium_Core_Ed25519::check_S_lt_L(self::substr($sig, 32, 32))
 799          ) {
 800              throw new SodiumException('S < L - Invalid signature');
 801          }
 802          if (ParagonIE_Sodium_Core_Ed25519::small_order($sig)) {
 803              throw new SodiumException('Signature is on too small of an order');
 804          }
 805          if ((self::chrToInt($sig[63]) & 224) !== 0) {
 806              throw new SodiumException('Invalid signature');
 807          }
 808          $d = 0;
 809          for ($i = 0; $i < 32; ++$i) {
 810              $d |= self::chrToInt($publicKey[$i]);
 811          }
 812          if ($d === 0) {
 813              throw new SodiumException('All zero public key');
 814          }
 815  
 816          if (!file_exists($filePath)) {
 817              throw new SodiumException('File does not exist');
 818          }
 819          /** @var int $size */
 820          $size = filesize($filePath);
 821          if (!is_int($size)) {
 822              throw new SodiumException('Could not obtain the file size');
 823          }
 824  
 825          /** @var resource $fp */
 826          $fp = fopen($filePath, 'rb');
 827          if (!is_resource($fp)) {
 828              throw new SodiumException('Could not open input file for reading');
 829          }
 830  
 831          /** @var bool The original value of ParagonIE_Sodium_Compat::$fastMult */
 832          $orig = ParagonIE_Sodium_Compat::$fastMult;
 833  
 834          // Set ParagonIE_Sodium_Compat::$fastMult to true to speed up verification.
 835          ParagonIE_Sodium_Compat::$fastMult = true;
 836          try {
 837              if (ParagonIE_Sodium_Core_Ed25519::small_order($publicKey)) {
 838                  throw new SodiumException('Public key has small order');
 839              }
 840              /** @var ParagonIE_Sodium_Core_Curve25519_Ge_P3 $A */
 841              $A = ParagonIE_Sodium_Core_Ed25519::ge_frombytes_negate_vartime($publicKey);
 842              if (!ParagonIE_Sodium_Core_Ed25519::is_on_main_subgroup($A)) {
 843                  throw new SodiumException('Public key is not on a member of the main subgroup');
 844              }
 845  
 846              $hs = hash_init('sha512');
 847              self::hash_update($hs, self::substr($sig, 0, 32));
 848              self::hash_update($hs, self::substr($publicKey, 0, 32));
 849              /** @var resource $hs */
 850              $hs = self::updateHashWithFile($hs, $fp, $size);
 851              /** @var string $hDigest */
 852              $hDigest = hash_final($hs, true);
 853  
 854              /** @var string $h */
 855              $h = ParagonIE_Sodium_Core_Ed25519::sc_reduce($hDigest) . self::substr($hDigest, 32);
 856  
 857              /** @var ParagonIE_Sodium_Core_Curve25519_Ge_P2 $R */
 858              $R = ParagonIE_Sodium_Core_Ed25519::ge_double_scalarmult_vartime(
 859                  $h,
 860                  $A,
 861                  self::substr($sig, 32)
 862              );
 863  
 864              /** @var string $rcheck */
 865              $rcheck = ParagonIE_Sodium_Core_Ed25519::ge_tobytes($R);
 866          } catch (Exception $ex) {
 867              fclose($fp);
 868              ParagonIE_Sodium_Compat::$fastMult = $orig;
 869              throw $ex;
 870          }
 871  
 872          // Close the file handle
 873          fclose($fp);
 874  
 875          // Reset ParagonIE_Sodium_Compat::$fastMult to what it was before.
 876          ParagonIE_Sodium_Compat::$fastMult = $orig;
 877          return self::verify_32($rcheck, self::substr($sig, 0, 32));
 878      }
 879  
 880      /**
 881       * @param resource $ifp
 882       * @param resource $ofp
 883       * @param int      $mlen
 884       * @param string   $nonce
 885       * @param string   $boxKeypair
 886       * @return bool
 887       * @throws SodiumException
 888       * @throws TypeError
 889       */
 890      protected static function box_encrypt($ifp, $ofp, $mlen, $nonce, $boxKeypair)
 891      {
 892          if (PHP_INT_SIZE === 4) {
 893              return self::secretbox_encrypt(
 894                  $ifp,
 895                  $ofp,
 896                  $mlen,
 897                  $nonce,
 898                  ParagonIE_Sodium_Crypto32::box_beforenm(
 899                      ParagonIE_Sodium_Crypto32::box_secretkey($boxKeypair),
 900                      ParagonIE_Sodium_Crypto32::box_publickey($boxKeypair)
 901                  )
 902              );
 903          }
 904          return self::secretbox_encrypt(
 905              $ifp,
 906              $ofp,
 907              $mlen,
 908              $nonce,
 909              ParagonIE_Sodium_Crypto::box_beforenm(
 910                  ParagonIE_Sodium_Crypto::box_secretkey($boxKeypair),
 911                  ParagonIE_Sodium_Crypto::box_publickey($boxKeypair)
 912              )
 913          );
 914      }
 915  
 916  
 917      /**
 918       * @param resource $ifp
 919       * @param resource $ofp
 920       * @param int      $mlen
 921       * @param string   $nonce
 922       * @param string   $boxKeypair
 923       * @return bool
 924       * @throws SodiumException
 925       * @throws TypeError
 926       */
 927      protected static function box_decrypt($ifp, $ofp, $mlen, $nonce, $boxKeypair)
 928      {
 929          if (PHP_INT_SIZE === 4) {
 930              return self::secretbox_decrypt(
 931                  $ifp,
 932                  $ofp,
 933                  $mlen,
 934                  $nonce,
 935                  ParagonIE_Sodium_Crypto32::box_beforenm(
 936                      ParagonIE_Sodium_Crypto32::box_secretkey($boxKeypair),
 937                      ParagonIE_Sodium_Crypto32::box_publickey($boxKeypair)
 938                  )
 939              );
 940          }
 941          return self::secretbox_decrypt(
 942              $ifp,
 943              $ofp,
 944              $mlen,
 945              $nonce,
 946              ParagonIE_Sodium_Crypto::box_beforenm(
 947                  ParagonIE_Sodium_Crypto::box_secretkey($boxKeypair),
 948                  ParagonIE_Sodium_Crypto::box_publickey($boxKeypair)
 949              )
 950          );
 951      }
 952  
 953      /**
 954       * Encrypt a file
 955       *
 956       * @param resource $ifp
 957       * @param resource $ofp
 958       * @param int $mlen
 959       * @param string $nonce
 960       * @param string $key
 961       * @return bool
 962       * @throws SodiumException
 963       * @throws TypeError
 964       */
 965      protected static function secretbox_encrypt($ifp, $ofp, $mlen, $nonce, $key)
 966      {
 967          if (PHP_INT_SIZE === 4) {
 968              return self::secretbox_encrypt_core32($ifp, $ofp, $mlen, $nonce, $key);
 969          }
 970  
 971          $plaintext = fread($ifp, 32);
 972          if (!is_string($plaintext)) {
 973              throw new SodiumException('Could not read input file');
 974          }
 975          $first32 = self::ftell($ifp);
 976  
 977          /** @var string $subkey */
 978          $subkey = ParagonIE_Sodium_Core_HSalsa20::hsalsa20($nonce, $key);
 979  
 980          /** @var string $realNonce */
 981          $realNonce = ParagonIE_Sodium_Core_Util::substr($nonce, 16, 8);
 982  
 983          /** @var string $block0 */
 984          $block0 = str_repeat("\x00", 32);
 985  
 986          /** @var int $mlen - Length of the plaintext message */
 987          $mlen0 = $mlen;
 988          if ($mlen0 > 64 - ParagonIE_Sodium_Crypto::secretbox_xsalsa20poly1305_ZEROBYTES) {
 989              $mlen0 = 64 - ParagonIE_Sodium_Crypto::secretbox_xsalsa20poly1305_ZEROBYTES;
 990          }
 991          $block0 .= ParagonIE_Sodium_Core_Util::substr($plaintext, 0, $mlen0);
 992  
 993          /** @var string $block0 */
 994          $block0 = ParagonIE_Sodium_Core_Salsa20::salsa20_xor(
 995              $block0,
 996              $realNonce,
 997              $subkey
 998          );
 999  
1000          $state = new ParagonIE_Sodium_Core_Poly1305_State(
1001              ParagonIE_Sodium_Core_Util::substr(
1002                  $block0,
1003                  0,
1004                  ParagonIE_Sodium_Crypto::onetimeauth_poly1305_KEYBYTES
1005              )
1006          );
1007  
1008          // Pre-write 16 blank bytes for the Poly1305 tag
1009          $start = self::ftell($ofp);
1010          fwrite($ofp, str_repeat("\x00", 16));
1011  
1012          /** @var string $c */
1013          $cBlock = ParagonIE_Sodium_Core_Util::substr(
1014              $block0,
1015              ParagonIE_Sodium_Crypto::secretbox_xsalsa20poly1305_ZEROBYTES
1016          );
1017          $state->update($cBlock);
1018          fwrite($ofp, $cBlock);
1019          $mlen -= 32;
1020  
1021          /** @var int $iter */
1022          $iter = 1;
1023  
1024          /** @var int $incr */
1025          $incr = self::BUFFER_SIZE >> 6;
1026  
1027          /*
1028           * Set the cursor to the end of the first half-block. All future bytes will
1029           * generated from salsa20_xor_ic, starting from 1 (second block).
1030           */
1031          fseek($ifp, $first32, SEEK_SET);
1032  
1033          while ($mlen > 0) {
1034              $blockSize = $mlen > self::BUFFER_SIZE
1035                  ? self::BUFFER_SIZE
1036                  : $mlen;
1037              $plaintext = fread($ifp, $blockSize);
1038              if (!is_string($plaintext)) {
1039                  throw new SodiumException('Could not read input file');
1040              }
1041              $cBlock = ParagonIE_Sodium_Core_Salsa20::salsa20_xor_ic(
1042                  $plaintext,
1043                  $realNonce,
1044                  $iter,
1045                  $subkey
1046              );
1047              fwrite($ofp, $cBlock, $blockSize);
1048              $state->update($cBlock);
1049  
1050              $mlen -= $blockSize;
1051              $iter += $incr;
1052          }
1053          try {
1054              ParagonIE_Sodium_Compat::memzero($block0);
1055              ParagonIE_Sodium_Compat::memzero($subkey);
1056          } catch (SodiumException $ex) {
1057              $block0 = null;
1058              $subkey = null;
1059          }
1060          $end = self::ftell($ofp);
1061  
1062          /*
1063           * Write the Poly1305 authentication tag that provides integrity
1064           * over the ciphertext (encrypt-then-MAC)
1065           */
1066          fseek($ofp, $start, SEEK_SET);
1067          fwrite($ofp, $state->finish(), ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_MACBYTES);
1068          fseek($ofp, $end, SEEK_SET);
1069          unset($state);
1070  
1071          return true;
1072      }
1073  
1074      /**
1075       * Decrypt a file
1076       *
1077       * @param resource $ifp
1078       * @param resource $ofp
1079       * @param int $mlen
1080       * @param string $nonce
1081       * @param string $key
1082       * @return bool
1083       * @throws SodiumException
1084       * @throws TypeError
1085       */
1086      protected static function secretbox_decrypt($ifp, $ofp, $mlen, $nonce, $key)
1087      {
1088          if (PHP_INT_SIZE === 4) {
1089              return self::secretbox_decrypt_core32($ifp, $ofp, $mlen, $nonce, $key);
1090          }
1091          $tag = fread($ifp, 16);
1092          if (!is_string($tag)) {
1093              throw new SodiumException('Could not read input file');
1094          }
1095  
1096          /** @var string $subkey */
1097          $subkey = ParagonIE_Sodium_Core_HSalsa20::hsalsa20($nonce, $key);
1098  
1099          /** @var string $realNonce */
1100          $realNonce = ParagonIE_Sodium_Core_Util::substr($nonce, 16, 8);
1101  
1102          /** @var string $block0 */
1103          $block0 = ParagonIE_Sodium_Core_Salsa20::salsa20(
1104              64,
1105              ParagonIE_Sodium_Core_Util::substr($nonce, 16, 8),
1106              $subkey
1107          );
1108  
1109          /* Verify the Poly1305 MAC -before- attempting to decrypt! */
1110          $state = new ParagonIE_Sodium_Core_Poly1305_State(self::substr($block0, 0, 32));
1111          if (!self::onetimeauth_verify($state, $ifp, $tag, $mlen)) {
1112              throw new SodiumException('Invalid MAC');
1113          }
1114  
1115          /*
1116           * Set the cursor to the end of the first half-block. All future bytes will
1117           * generated from salsa20_xor_ic, starting from 1 (second block).
1118           */
1119          $first32 = fread($ifp, 32);
1120          if (!is_string($first32)) {
1121              throw new SodiumException('Could not read input file');
1122          }
1123          $first32len = self::strlen($first32);
1124          fwrite(
1125              $ofp,
1126              self::xorStrings(
1127                  self::substr($block0, 32, $first32len),
1128                  self::substr($first32, 0, $first32len)
1129              )
1130          );
1131          $mlen -= 32;
1132  
1133          /** @var int $iter */
1134          $iter = 1;
1135  
1136          /** @var int $incr */
1137          $incr = self::BUFFER_SIZE >> 6;
1138  
1139          /* Decrypts ciphertext, writes to output file. */
1140          while ($mlen > 0) {
1141              $blockSize = $mlen > self::BUFFER_SIZE
1142                  ? self::BUFFER_SIZE
1143                  : $mlen;
1144              $ciphertext = fread($ifp, $blockSize);
1145              if (!is_string($ciphertext)) {
1146                  throw new SodiumException('Could not read input file');
1147              }
1148              $pBlock = ParagonIE_Sodium_Core_Salsa20::salsa20_xor_ic(
1149                  $ciphertext,
1150                  $realNonce,
1151                  $iter,
1152                  $subkey
1153              );
1154              fwrite($ofp, $pBlock, $blockSize);
1155              $mlen -= $blockSize;
1156              $iter += $incr;
1157          }
1158          return true;
1159      }
1160  
1161      /**
1162       * @param ParagonIE_Sodium_Core_Poly1305_State $state
1163       * @param resource $ifp
1164       * @param string $tag
1165       * @param int $mlen
1166       * @return bool
1167       * @throws SodiumException
1168       * @throws TypeError
1169       */
1170      protected static function onetimeauth_verify(
1171          ParagonIE_Sodium_Core_Poly1305_State $state,
1172          $ifp,
1173          $tag = '',
1174          $mlen = 0
1175      ) {
1176          /** @var int $pos */
1177          $pos = self::ftell($ifp);
1178  
1179          /** @var int $iter */
1180          $iter = 1;
1181  
1182          /** @var int $incr */
1183          $incr = self::BUFFER_SIZE >> 6;
1184  
1185          while ($mlen > 0) {
1186              $blockSize = $mlen > self::BUFFER_SIZE
1187                  ? self::BUFFER_SIZE
1188                  : $mlen;
1189              $ciphertext = fread($ifp, $blockSize);
1190              if (!is_string($ciphertext)) {
1191                  throw new SodiumException('Could not read input file');
1192              }
1193              $state->update($ciphertext);
1194              $mlen -= $blockSize;
1195              $iter += $incr;
1196          }
1197          $res = ParagonIE_Sodium_Core_Util::verify_16($tag, $state->finish());
1198  
1199          fseek($ifp, $pos, SEEK_SET);
1200          return $res;
1201      }
1202  
1203      /**
1204       * @param string $outputFile
1205       * @return resource|bool
1206       */
1207      protected static function openOutputFile($outputFile)
1208      {
1209          $destination = @fopen($outputFile, 'r+b');
1210          return is_resource($destination) ? $destination : @fopen($outputFile, 'x+b');
1211      }
1212  
1213      /**
1214       * @param resource $tmp
1215       * @param resource $destination
1216       * @return void
1217       * @throws SodiumException
1218       */
1219      protected static function commitAuthenticatedOutput($tmp, $destination)
1220      {
1221          if (fseek($tmp, 0) !== 0) {
1222              throw new SodiumException('Could not rewind temporary output file');
1223          }
1224          if (fseek($destination, 0) !== 0 || !ftruncate($destination, 0)) {
1225              throw new SodiumException('Could not prepare output file for writing');
1226          }
1227          if (stream_copy_to_stream($tmp, $destination) === false) {
1228              throw new SodiumException('Could not write to output file');
1229          }
1230      }
1231  
1232      /**
1233       * Update a hash context with the contents of a file, without
1234       * loading the entire file into memory.
1235       *
1236       * @param resource|HashContext $hash
1237       * @param resource $fp
1238       * @param int $size
1239       * @return resource|object Resource on PHP < 7.2, HashContext object on PHP >= 7.2
1240       * @throws SodiumException
1241       * @throws TypeError
1242       * @psalm-suppress PossiblyInvalidArgument
1243       *                 PHP 7.2 changes from a resource to an object,
1244       *                 which causes Psalm to complain about an error.
1245       * @psalm-suppress TypeCoercion
1246       *                 Ditto.
1247       */
1248      public static function updateHashWithFile($hash, $fp, $size = 0)
1249      {
1250          /* Type checks: */
1251          if (PHP_VERSION_ID < 70200) {
1252              if (!is_resource($hash)) {
1253                  throw new TypeError('Argument 1 must be a resource, ' . gettype($hash) . ' given.');
1254              }
1255          } else {
1256              if (!is_object($hash)) {
1257                  throw new TypeError('Argument 1 must be an object (PHP 7.2+), ' . gettype($hash) . ' given.');
1258              }
1259          }
1260  
1261          if (!is_resource($fp)) {
1262              throw new TypeError('Argument 2 must be a resource, ' . gettype($fp) . ' given.');
1263          }
1264          if (!is_int($size)) {
1265              throw new TypeError('Argument 3 must be an integer, ' . gettype($size) . ' given.');
1266          }
1267  
1268          /** @var int $originalPosition */
1269          $originalPosition = self::ftell($fp);
1270  
1271          // Move file pointer to beginning of file
1272          fseek($fp, 0, SEEK_SET);
1273          for ($i = 0; $i < $size; $i += self::BUFFER_SIZE) {
1274              /** @var string|bool $message */
1275              $message = fread(
1276                  $fp,
1277                  ($size - $i) > self::BUFFER_SIZE
1278                      ? $size - $i
1279                      : self::BUFFER_SIZE
1280              );
1281              if (!is_string($message)) {
1282                  throw new SodiumException('Unexpected error reading from file.');
1283              }
1284              /** @var string $message */
1285              /** @psalm-suppress InvalidArgument */
1286              self::hash_update($hash, $message);
1287          }
1288          // Reset file pointer's position
1289          fseek($fp, $originalPosition, SEEK_SET);
1290          return $hash;
1291      }
1292  
1293      /**
1294       * Sign a file (rather than a string). Uses less memory than
1295       * ParagonIE_Sodium_Compat::crypto_sign_detached(), but produces
1296       * the same result. (32-bit)
1297       *
1298       * @param string $filePath  Absolute path to a file on the filesystem
1299       * @param string $secretKey Secret signing key
1300       *
1301       * @return string           Ed25519 signature
1302       * @throws SodiumException
1303       * @throws TypeError
1304       */
1305      private static function sign_core32($filePath, $secretKey)
1306      {
1307          $size = filesize($filePath);
1308          if (!is_int($size)) {
1309              throw new SodiumException('Could not obtain the file size');
1310          }
1311  
1312          $fp = fopen($filePath, 'rb');
1313          if (!is_resource($fp)) {
1314              throw new SodiumException('Could not open input file for reading');
1315          }
1316  
1317          /** @var string $az */
1318          $az = hash('sha512', self::substr($secretKey, 0, 32), true);
1319  
1320          $az[0] = self::intToChr(self::chrToInt($az[0]) & 248);
1321          $az[31] = self::intToChr((self::chrToInt($az[31]) & 63) | 64);
1322  
1323          $hs = hash_init('sha512');
1324          self::hash_update($hs, self::substr($az, 32, 32));
1325          /** @var resource $hs */
1326          $hs = self::updateHashWithFile($hs, $fp, $size);
1327  
1328          $nonceHash = hash_final($hs, true);
1329          $pk = self::substr($secretKey, 32, 32);
1330          $nonce = ParagonIE_Sodium_Core32_Ed25519::sc_reduce($nonceHash) . self::substr($nonceHash, 32);
1331          $sig = ParagonIE_Sodium_Core32_Ed25519::ge_p3_tobytes(
1332              ParagonIE_Sodium_Core32_Ed25519::ge_scalarmult_base($nonce)
1333          );
1334  
1335          $hs = hash_init('sha512');
1336          self::hash_update($hs, self::substr($sig, 0, 32));
1337          self::hash_update($hs, self::substr($pk, 0, 32));
1338          /** @var resource $hs */
1339          $hs = self::updateHashWithFile($hs, $fp, $size);
1340  
1341          $hramHash = hash_final($hs, true);
1342  
1343          $hram = ParagonIE_Sodium_Core32_Ed25519::sc_reduce($hramHash);
1344  
1345          $sigAfter = ParagonIE_Sodium_Core32_Ed25519::sc_muladd($hram, $az, $nonce);
1346  
1347          /** @var string $sig */
1348          $sig = self::substr($sig, 0, 32) . self::substr($sigAfter, 0, 32);
1349  
1350          try {
1351              ParagonIE_Sodium_Compat::memzero($az);
1352          } catch (SodiumException $ex) {
1353              $az = null;
1354          }
1355          fclose($fp);
1356          return $sig;
1357      }
1358  
1359      /**
1360       *
1361       * Verify a file (rather than a string). Uses less memory than
1362       * ParagonIE_Sodium_Compat::crypto_sign_verify_detached(), but
1363       * produces the same result. (32-bit)
1364       *
1365       * @param string $sig       Ed25519 signature
1366       * @param string $filePath  Absolute path to a file on the filesystem
1367       * @param string $publicKey Signing public key
1368       *
1369       * @return bool
1370       * @throws SodiumException
1371       * @throws Exception
1372       */
1373      public static function verify_core32($sig, $filePath, $publicKey)
1374      {
1375          /* Security checks */
1376          if (ParagonIE_Sodium_Core32_Ed25519::check_S_lt_L(self::substr($sig, 32, 32))) {
1377              throw new SodiumException('S < L - Invalid signature');
1378          }
1379          if (ParagonIE_Sodium_Core32_Ed25519::small_order($sig)) {
1380              throw new SodiumException('Signature is on too small of an order');
1381          }
1382  
1383          if ((self::chrToInt($sig[63]) & 224) !== 0) {
1384              throw new SodiumException('Invalid signature');
1385          }
1386          $d = 0;
1387          for ($i = 0; $i < 32; ++$i) {
1388              $d |= self::chrToInt($publicKey[$i]);
1389          }
1390          if ($d === 0) {
1391              throw new SodiumException('All zero public key');
1392          }
1393  
1394          /** @var int|bool $size */
1395          $size = filesize($filePath);
1396          if (!is_int($size)) {
1397              throw new SodiumException('Could not obtain the file size');
1398          }
1399          /** @var int $size */
1400  
1401          /** @var resource|bool $fp */
1402          $fp = fopen($filePath, 'rb');
1403          if (!is_resource($fp)) {
1404              throw new SodiumException('Could not open input file for reading');
1405          }
1406          /** @var resource $fp */
1407  
1408          /** @var bool The original value of ParagonIE_Sodium_Compat::$fastMult */
1409          $orig = ParagonIE_Sodium_Compat::$fastMult;
1410  
1411          // Set ParagonIE_Sodium_Compat::$fastMult to true to speed up verification.
1412          ParagonIE_Sodium_Compat::$fastMult = true;
1413          try {
1414              if (ParagonIE_Sodium_Core32_Ed25519::small_order($publicKey)) {
1415                  throw new SodiumException('Public key has small order');
1416              }
1417              /** @var ParagonIE_Sodium_Core32_Curve25519_Ge_P3 $A */
1418              $A = ParagonIE_Sodium_Core32_Ed25519::ge_frombytes_negate_vartime($publicKey);
1419              if (!ParagonIE_Sodium_Core32_Ed25519::is_on_main_subgroup($A)) {
1420                  throw new SodiumException('Public key is not on a member of the main subgroup');
1421              }
1422  
1423              $hs = hash_init('sha512');
1424              self::hash_update($hs, self::substr($sig, 0, 32));
1425              self::hash_update($hs, self::substr($publicKey, 0, 32));
1426              /** @var resource $hs */
1427              $hs = self::updateHashWithFile($hs, $fp, $size);
1428              /** @var string $hDigest */
1429              $hDigest = hash_final($hs, true);
1430  
1431              /** @var string $h */
1432              $h = ParagonIE_Sodium_Core32_Ed25519::sc_reduce($hDigest) . self::substr($hDigest, 32);
1433  
1434              /** @var ParagonIE_Sodium_Core32_Curve25519_Ge_P2 $R */
1435              $R = ParagonIE_Sodium_Core32_Ed25519::ge_double_scalarmult_vartime(
1436                  $h,
1437                  $A,
1438                  self::substr($sig, 32)
1439              );
1440  
1441              /** @var string $rcheck */
1442              $rcheck = ParagonIE_Sodium_Core32_Ed25519::ge_tobytes($R);
1443          } catch (Exception $ex) {
1444              fclose($fp);
1445              ParagonIE_Sodium_Compat::$fastMult = $orig;
1446              throw $ex;
1447          }
1448  
1449          // Close the file handle
1450          fclose($fp);
1451  
1452          // Reset ParagonIE_Sodium_Compat::$fastMult to what it was before.
1453          ParagonIE_Sodium_Compat::$fastMult = $orig;
1454          return self::verify_32($rcheck, self::substr($sig, 0, 32));
1455      }
1456  
1457      /**
1458       * Encrypt a file (32-bit)
1459       *
1460       * @param resource $ifp
1461       * @param resource $ofp
1462       * @param int $mlen
1463       * @param string $nonce
1464       * @param string $key
1465       * @return bool
1466       * @throws SodiumException
1467       * @throws TypeError
1468       */
1469      protected static function secretbox_encrypt_core32($ifp, $ofp, $mlen, $nonce, $key)
1470      {
1471          $plaintext = fread($ifp, 32);
1472          if (!is_string($plaintext)) {
1473              throw new SodiumException('Could not read input file');
1474          }
1475          $first32 = self::ftell($ifp);
1476  
1477          /** @var string $subkey */
1478          $subkey = ParagonIE_Sodium_Core32_HSalsa20::hsalsa20($nonce, $key);
1479  
1480          /** @var string $realNonce */
1481          $realNonce = ParagonIE_Sodium_Core32_Util::substr($nonce, 16, 8);
1482  
1483          /** @var string $block0 */
1484          $block0 = str_repeat("\x00", 32);
1485  
1486          /** @var int $mlen - Length of the plaintext message */
1487          $mlen0 = $mlen;
1488          if ($mlen0 > 64 - ParagonIE_Sodium_Crypto::secretbox_xsalsa20poly1305_ZEROBYTES) {
1489              $mlen0 = 64 - ParagonIE_Sodium_Crypto::secretbox_xsalsa20poly1305_ZEROBYTES;
1490          }
1491          $block0 .= ParagonIE_Sodium_Core32_Util::substr($plaintext, 0, $mlen0);
1492  
1493          /** @var string $block0 */
1494          $block0 = ParagonIE_Sodium_Core32_Salsa20::salsa20_xor(
1495              $block0,
1496              $realNonce,
1497              $subkey
1498          );
1499  
1500          $state = new ParagonIE_Sodium_Core32_Poly1305_State(
1501              ParagonIE_Sodium_Core32_Util::substr(
1502                  $block0,
1503                  0,
1504                  ParagonIE_Sodium_Crypto::onetimeauth_poly1305_KEYBYTES
1505              )
1506          );
1507  
1508          // Pre-write 16 blank bytes for the Poly1305 tag
1509          $start = self::ftell($ofp);
1510          fwrite($ofp, str_repeat("\x00", 16));
1511  
1512          /** @var string $c */
1513          $cBlock = ParagonIE_Sodium_Core32_Util::substr(
1514              $block0,
1515              ParagonIE_Sodium_Crypto::secretbox_xsalsa20poly1305_ZEROBYTES
1516          );
1517          $state->update($cBlock);
1518          fwrite($ofp, $cBlock);
1519          $mlen -= 32;
1520  
1521          /** @var int $iter */
1522          $iter = 1;
1523  
1524          /** @var int $incr */
1525          $incr = self::BUFFER_SIZE >> 6;
1526  
1527          /*
1528           * Set the cursor to the end of the first half-block. All future bytes will
1529           * generated from salsa20_xor_ic, starting from 1 (second block).
1530           */
1531          fseek($ifp, $first32, SEEK_SET);
1532  
1533          while ($mlen > 0) {
1534              $blockSize = $mlen > self::BUFFER_SIZE
1535                  ? self::BUFFER_SIZE
1536                  : $mlen;
1537              $plaintext = fread($ifp, $blockSize);
1538              if (!is_string($plaintext)) {
1539                  throw new SodiumException('Could not read input file');
1540              }
1541              $cBlock = ParagonIE_Sodium_Core32_Salsa20::salsa20_xor_ic(
1542                  $plaintext,
1543                  $realNonce,
1544                  $iter,
1545                  $subkey
1546              );
1547              fwrite($ofp, $cBlock, $blockSize);
1548              $state->update($cBlock);
1549  
1550              $mlen -= $blockSize;
1551              $iter += $incr;
1552          }
1553          try {
1554              ParagonIE_Sodium_Compat::memzero($block0);
1555              ParagonIE_Sodium_Compat::memzero($subkey);
1556          } catch (SodiumException $ex) {
1557              $block0 = null;
1558              $subkey = null;
1559          }
1560          $end = self::ftell($ofp);
1561  
1562          /*
1563           * Write the Poly1305 authentication tag that provides integrity
1564           * over the ciphertext (encrypt-then-MAC)
1565           */
1566          fseek($ofp, $start, SEEK_SET);
1567          fwrite($ofp, $state->finish(), ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_MACBYTES);
1568          fseek($ofp, $end, SEEK_SET);
1569          unset($state);
1570  
1571          return true;
1572      }
1573  
1574      /**
1575       * Decrypt a file (32-bit)
1576       *
1577       * @param resource $ifp
1578       * @param resource $ofp
1579       * @param int $mlen
1580       * @param string $nonce
1581       * @param string $key
1582       * @return bool
1583       * @throws SodiumException
1584       * @throws TypeError
1585       */
1586      protected static function secretbox_decrypt_core32($ifp, $ofp, $mlen, $nonce, $key)
1587      {
1588          $tag = fread($ifp, 16);
1589          if (!is_string($tag)) {
1590              throw new SodiumException('Could not read input file');
1591          }
1592  
1593          /** @var string $subkey */
1594          $subkey = ParagonIE_Sodium_Core32_HSalsa20::hsalsa20($nonce, $key);
1595  
1596          /** @var string $realNonce */
1597          $realNonce = ParagonIE_Sodium_Core32_Util::substr($nonce, 16, 8);
1598  
1599          /** @var string $block0 */
1600          $block0 = ParagonIE_Sodium_Core32_Salsa20::salsa20(
1601              64,
1602              ParagonIE_Sodium_Core32_Util::substr($nonce, 16, 8),
1603              $subkey
1604          );
1605  
1606          /* Verify the Poly1305 MAC -before- attempting to decrypt! */
1607          $state = new ParagonIE_Sodium_Core32_Poly1305_State(self::substr($block0, 0, 32));
1608          if (!self::onetimeauth_verify_core32($state, $ifp, $tag, $mlen)) {
1609              throw new SodiumException('Invalid MAC');
1610          }
1611  
1612          /*
1613           * Set the cursor to the end of the first half-block. All future bytes will
1614           * generated from salsa20_xor_ic, starting from 1 (second block).
1615           */
1616          $first32 = fread($ifp, 32);
1617          if (!is_string($first32)) {
1618              throw new SodiumException('Could not read input file');
1619          }
1620          $first32len = self::strlen($first32);
1621          fwrite(
1622              $ofp,
1623              self::xorStrings(
1624                  self::substr($block0, 32, $first32len),
1625                  self::substr($first32, 0, $first32len)
1626              )
1627          );
1628          $mlen -= 32;
1629  
1630          /** @var int $iter */
1631          $iter = 1;
1632  
1633          /** @var int $incr */
1634          $incr = self::BUFFER_SIZE >> 6;
1635  
1636          /* Decrypts ciphertext, writes to output file. */
1637          while ($mlen > 0) {
1638              $blockSize = $mlen > self::BUFFER_SIZE
1639                  ? self::BUFFER_SIZE
1640                  : $mlen;
1641              $ciphertext = fread($ifp, $blockSize);
1642              if (!is_string($ciphertext)) {
1643                  throw new SodiumException('Could not read input file');
1644              }
1645              $pBlock = ParagonIE_Sodium_Core32_Salsa20::salsa20_xor_ic(
1646                  $ciphertext,
1647                  $realNonce,
1648                  $iter,
1649                  $subkey
1650              );
1651              fwrite($ofp, $pBlock, $blockSize);
1652              $mlen -= $blockSize;
1653              $iter += $incr;
1654          }
1655          return true;
1656      }
1657  
1658      /**
1659       * One-time message authentication for 32-bit systems
1660       *
1661       * @param ParagonIE_Sodium_Core32_Poly1305_State $state
1662       * @param resource $ifp
1663       * @param string $tag
1664       * @param int $mlen
1665       * @return bool
1666       * @throws SodiumException
1667       * @throws TypeError
1668       */
1669      protected static function onetimeauth_verify_core32(
1670          ParagonIE_Sodium_Core32_Poly1305_State $state,
1671          $ifp,
1672          $tag = '',
1673          $mlen = 0
1674      ) {
1675          /** @var int $pos */
1676          $pos = self::ftell($ifp);
1677  
1678          while ($mlen > 0) {
1679              $blockSize = $mlen > self::BUFFER_SIZE
1680                  ? self::BUFFER_SIZE
1681                  : $mlen;
1682              $ciphertext = fread($ifp, $blockSize);
1683              if (!is_string($ciphertext)) {
1684                  throw new SodiumException('Could not read input file');
1685              }
1686              $state->update($ciphertext);
1687              $mlen -= $blockSize;
1688          }
1689          $res = ParagonIE_Sodium_Core32_Util::verify_16($tag, $state->finish());
1690  
1691          fseek($ifp, $pos, SEEK_SET);
1692          return $res;
1693      }
1694  
1695      /**
1696       * @param resource $resource
1697       * @return int
1698       * @throws SodiumException
1699       */
1700      private static function ftell($resource)
1701      {
1702          $return = ftell($resource);
1703          if (!is_int($return)) {
1704              throw new SodiumException('ftell() returned false');
1705          }
1706          return (int) $return;
1707      }
1708  }


Generated : Tue Nov 24 08:20:01 2026 Cross-referenced by PHPXref