You are here

public static function ParagonIE_Sodium_File::secretbox in Automatic Updates 8

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

Encrypt a file (rather than a string). Uses less memory than ParagonIE_Sodium_Compat::crypto_secretbox(), but produces the same result.

Parameters

string $inputFile Absolute path to a file on the filesystem:

string $outputFile Absolute path to a file on the filesystem:

string $nonce Number to be used only once:

string $key Encryption key:

Return value

bool

Throws

SodiumException

TypeError

File

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

Class

ParagonIE_Sodium_File
Class ParagonIE_Sodium_File

Code

public static function secretbox($inputFile, $outputFile, $nonce, $key) {

  /* Type checks: */
  if (!is_string($inputFile)) {
    throw new TypeError('Argument 1 must be a string, ' . gettype($inputFile) . ' given..');
  }
  if (!is_string($outputFile)) {
    throw new TypeError('Argument 2 must be a string, ' . gettype($outputFile) . ' given.');
  }
  if (!is_string($nonce)) {
    throw new TypeError('Argument 3 must be a string, ' . gettype($nonce) . ' given.');
  }

  /* Input validation: */
  if (self::strlen($nonce) !== ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_NONCEBYTES) {
    throw new TypeError('Argument 3 must be CRYPTO_SECRETBOX_NONCEBYTES bytes');
  }
  if (!is_string($key)) {
    throw new TypeError('Argument 4 must be a string, ' . gettype($key) . ' given.');
  }
  if (self::strlen($key) !== ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_KEYBYTES) {
    throw new TypeError('Argument 4 must be CRYPTO_SECRETBOX_KEYBYTES bytes');
  }

  /** @var int $size */
  $size = filesize($inputFile);
  if (!is_int($size)) {
    throw new SodiumException('Could not obtain the file size');
  }

  /** @var resource $ifp */
  $ifp = fopen($inputFile, 'rb');
  if (!is_resource($ifp)) {
    throw new SodiumException('Could not open input file for reading');
  }

  /** @var resource $ofp */
  $ofp = fopen($outputFile, 'wb');
  if (!is_resource($ofp)) {
    fclose($ifp);
    throw new SodiumException('Could not open output file for writing');
  }
  $res = self::secretbox_encrypt($ifp, $ofp, $size, $nonce, $key);
  fclose($ifp);
  fclose($ofp);
  return $res;
}