You are here

protected static function ParagonIE_Sodium_File::secretbox_decrypt_core32 in Automatic Updates 8

Same name and namespace in other branches
  1. 7 vendor/paragonie/sodium_compat/src/File.php \ParagonIE_Sodium_File::secretbox_decrypt_core32()

Decrypt a file (32-bit)

Parameters

resource $ifp:

resource $ofp:

int $mlen:

string $nonce:

string $key:

Return value

bool

Throws

SodiumException

TypeError

1 call to ParagonIE_Sodium_File::secretbox_decrypt_core32()
ParagonIE_Sodium_File::secretbox_decrypt in vendor/paragonie/sodium_compat/src/File.php
Decrypt a file

File

vendor/paragonie/sodium_compat/src/File.php, line 1436

Class

ParagonIE_Sodium_File
Class ParagonIE_Sodium_File

Code

protected static function secretbox_decrypt_core32($ifp, $ofp, $mlen, $nonce, $key) {
  $tag = fread($ifp, 16);
  if (!is_string($tag)) {
    throw new SodiumException('Could not read input file');
  }

  /** @var string $subkey */
  $subkey = ParagonIE_Sodium_Core32_HSalsa20::hsalsa20($nonce, $key);

  /** @var string $realNonce */
  $realNonce = ParagonIE_Sodium_Core32_Util::substr($nonce, 16, 8);

  /** @var string $block0 */
  $block0 = ParagonIE_Sodium_Core32_Salsa20::salsa20(64, ParagonIE_Sodium_Core32_Util::substr($nonce, 16, 8), $subkey);

  /* Verify the Poly1305 MAC -before- attempting to decrypt! */
  $state = new ParagonIE_Sodium_Core32_Poly1305_State(self::substr($block0, 0, 32));
  if (!self::onetimeauth_verify_core32($state, $ifp, $tag, $mlen)) {
    throw new SodiumException('Invalid MAC');
  }

  /*
   * Set the cursor to the end of the first half-block. All future bytes will
   * generated from salsa20_xor_ic, starting from 1 (second block).
   */
  $first32 = fread($ifp, 32);
  if (!is_string($first32)) {
    throw new SodiumException('Could not read input file');
  }
  $first32len = self::strlen($first32);
  fwrite($ofp, self::xorStrings(self::substr($block0, 32, $first32len), self::substr($first32, 0, $first32len)));
  $mlen -= 32;

  /** @var int $iter */
  $iter = 1;

  /** @var int $incr */
  $incr = self::BUFFER_SIZE >> 6;

  /* Decrypts ciphertext, writes to output file. */
  while ($mlen > 0) {
    $blockSize = $mlen > self::BUFFER_SIZE ? self::BUFFER_SIZE : $mlen;
    $ciphertext = fread($ifp, $blockSize);
    if (!is_string($ciphertext)) {
      throw new SodiumException('Could not read input file');
    }
    $pBlock = ParagonIE_Sodium_Core32_Salsa20::salsa20_xor_ic($ciphertext, $realNonce, $iter, $subkey);
    fwrite($ofp, $pBlock, $blockSize);
    $mlen -= $blockSize;
    $iter += $incr;
  }
  return true;
}