public function testFileHash() { $filename = \tempnam('/tmp', 'x'); $buf = \Sodium\randombytes_buf(65537); \file_put_contents($filename, $buf); $fileOne = new ReadOnlyFile($filename); $fp = \fopen($filename, 'rb'); $fileTwo = new ReadOnlyFile($fp); $this->assertSame($fileOne->getHash(), $fileTwo->getHash()); \fclose($fp); }
/** * Stream encryption - Do not call directly * * @param ReadOnlyFile $input * @param MutableFile $output * @param EncryptionKey $encKey * @param string $nonce * @param resource $mac (hash context) * @param Config $config * @throws FileAlert\AccessDenied */ private static final function streamEncrypt(ReadOnlyFile $input, MutableFile $output, KeyInterface $encKey, $nonce, $mac, Config $config) { if (!$encKey instanceof EncryptionKey) { throw new \ParagonIE\Halite\Alerts\InvalidKey('Argument 3: Expected an instance of EncryptionKey'); } $initHash = $input->getHash(); // Begin the streaming decryption $size = $input->getSize(); while ($input->remainingBytes() > 0) { $read = $input->readBytes($input->getPos() + $config->BUFFER > $size ? $size - $input->getPos() : $config->BUFFER); $encrypted = \Sodium\crypto_stream_xor($read, $nonce, $encKey->get()); \hash_update($mac, $encrypted); $output->writeBytes($encrypted); \Sodium\increment($nonce); } \Sodium\memzero($nonce); // Check that our input file was not modified before we MAC it if (!\hash_equals($input->gethash(), $initHash)) { throw new CryptoException\FileModified('Read-only file has been modified since it was opened for reading'); } return $output->writeBytes(\hash_final($mac, true)); }