Пример #1
0
 /**
  * Decrypt the contents of a file handle $inputHandle and store the results
  * in $outputHandle using HKDF of $key to decrypt then verify
  *
  * @param resource $inputHandle
  * @param resource $outputHandle
  * @param Key $key
  * @return boolean
  */
 public static function decryptResource($inputHandle, $outputHandle, Key $key)
 {
     // Because we don't have strict typing in PHP 5
     if (!\is_resource($inputHandle)) {
         throw new Ex\InvalidInput('Input handle must be a resource!');
     }
     if (!\is_resource($outputHandle)) {
         throw new Ex\InvalidInput('Output handle must be a resource!');
     }
     // Parse the header.
     $header = self::readBytes($inputHandle, Core::HEADER_VERSION_SIZE);
     $config = self::getFileVersionConfigFromHeader($header, Core::CURRENT_FILE_VERSION);
     // Let's add this check before anything
     if (!\in_array($config->hashFunctionName(), \hash_algos())) {
         throw new Ex\CannotPerformOperationException('The specified hash function does not exist');
     }
     // Let's grab the file salt.
     $file_salt = self::readBytes($inputHandle, $config->saltByteSize());
     // For storing MACs of each buffer chunk
     $macs = [];
     /**
      * 1. We need to decode some values from our files
      */
     /**
      * Let's split our keys
      *
      * $ekey -- Encryption Key -- used for AES
      */
     $ekey = Core::HKDF($config->hashFunctionName(), $key->getRawBytes(), $config->keyByteSize(), $config->encryptionInfoString(), $file_salt, $config);
     /**
      * $akey -- Authentication Key -- used for HMAC
      */
     $akey = Core::HKDF($config->hashFunctionName(), $key->getRawBytes(), $config->keyByteSize(), $config->authenticationInfoString(), $file_salt, $config);
     /**
      * Grab our IV from the encrypted message
      *
      * It should be the first N blocks of the file (N = 16)
      */
     $ivsize = \openssl_cipher_iv_length($config->cipherMethod());
     $iv = self::readBytes($inputHandle, $ivsize);
     // How much do we increase the counter after each buffered encryption to prevent nonce reuse
     $inc = $config->bufferByteSize() / $config->blockByteSize();
     $thisIv = $iv;
     /**
      * Let's grab our MAC
      *
      * It should be the last N blocks of the file (N = 32)
      */
     if (\fseek($inputHandle, -1 * $config->macByteSize(), SEEK_END) === false) {
         throw new Ex\CannotPerformOperationException('Cannot seek to beginning of MAC within input file');
     }
     // Grab our last position of ciphertext before we read the MAC
     $cipher_end = \ftell($inputHandle);
     if ($cipher_end === false) {
         throw new Ex\CannotPerformOperationException('Cannot read input file');
     }
     --$cipher_end;
     // We need to subtract one
     // We keep our MAC stored in this variable
     $stored_mac = self::readBytes($inputHandle, $config->macByteSize());
     /**
      * We begin recalculating the HMAC for the entire file...
      */
     $hmac = \hash_init($config->hashFunctionName(), HASH_HMAC, $akey);
     if ($hmac === false) {
         throw new Ex\CannotPerformOperationException('Cannot initialize a hash context');
     }
     /**
      * Reset file pointer to the beginning of the file after the header
      */
     if (\fseek($inputHandle, Core::HEADER_VERSION_SIZE, SEEK_SET) === false) {
         throw new Ex\CannotPerformOperationException('Cannot read seek within input file');
     }
     /**
      * Set it to the first non-salt and non-IV byte
      */
     if (\fseek($inputHandle, $config->saltByteSize() + $ivsize, SEEK_CUR) === false) {
         throw new Ex\CannotPerformOperationException('Cannot read seek input file to beginning of ciphertext');
     }
     /**
      * 2. Let's recalculate the MAC
      */
     /**
      * Let's initialize our $hmac hasher with our Salt and IV
      */
     \hash_update($hmac, $header);
     \hash_update($hmac, $file_salt);
     \hash_update($hmac, $iv);
     $hmac2 = \hash_copy($hmac);
     $break = false;
     while (!$break) {
         /**
          * First, grab the current position
          */
         $pos = \ftell($inputHandle);
         if ($pos === false) {
             throw new Ex\CannotPerformOperationException('Could not get current position in input file during decryption');
         }
         /**
          * Would a full DBUFFER read put it past the end of the
          * ciphertext? If so, only return a portion of the file.
          */
         if ($pos + $config->bufferByteSize() >= $cipher_end) {
             $break = true;
             $read = self::readBytes($inputHandle, $cipher_end - $pos + 1);
         } else {
             $read = self::readBytes($inputHandle, $config->bufferByteSize());
         }
         if ($read === false) {
             throw new Ex\CannotPerformOperationException('Could not read input file during decryption');
         }
         /**
          * We're updating our HMAC and nothing else
          */
         \hash_update($hmac, $read);
         /**
          * Store a MAC of each chunk
          */
         $chunkMAC = \hash_copy($hmac);
         if ($chunkMAC === false) {
             throw new Ex\CannotPerformOperationException('Cannot duplicate a hash context');
         }
         $macs[] = \hash_final($chunkMAC);
     }
     /**
      * We should now have enough data to generate an identical HMAC
      */
     $finalHMAC = \hash_final($hmac, true);
     /**
      * 3. Did we match?
      */
     if (!Core::hashEquals($finalHMAC, $stored_mac)) {
         throw new Ex\InvalidCiphertextException('Message Authentication failure; tampering detected.');
     }
     /**
      * 4. Okay, let's begin decrypting
      */
     /**
      * Return file pointer to the first non-header, non-IV byte in the file
      */
     if (\fseek($inputHandle, $config->saltByteSize() + $ivsize + Core::HEADER_VERSION_SIZE, SEEK_SET) === false) {
         throw new Ex\CannotPerformOperationException('Could not move the input file pointer during decryption');
     }
     /**
      * Should we break the writing?
      */
     $breakW = false;
     /**
      * This loop writes plaintext to the destination file:
      */
     while (!$breakW) {
         /**
          * Get the current position
          */
         $pos = \ftell($inputHandle);
         if ($pos === false) {
             throw new Ex\CannotPerformOperationException('Could not get current position in input file during decryption');
         }
         /**
          * Would a full BUFFER read put it past the end of the
          * ciphertext? If so, only return a portion of the file.
          */
         if ($pos + $config->bufferByteSize() >= $cipher_end) {
             $breakW = true;
             $read = self::readBytes($inputHandle, $cipher_end - $pos + 1);
         } else {
             $read = self::readBytes($inputHandle, $config->bufferByteSize());
         }
         /**
          * Recalculate the MAC, compare with the one stored in the $macs
          * array to ensure attackers couldn't tamper with the file
          * after MAC verification
          */
         \hash_update($hmac2, $read);
         $calcMAC = \hash_copy($hmac2);
         if ($calcMAC === false) {
             throw new Ex\CannotPerformOperationException('Cannot duplicate a hash context');
         }
         $calc = \hash_final($calcMAC);
         if (empty($macs)) {
             throw new Ex\InvalidCiphertextException('File was modified after MAC verification');
         } elseif (!Core::hashEquals(\array_shift($macs), $calc)) {
             throw new Ex\InvalidCiphertextException('File was modified after MAC verification');
         }
         $thisIv = Core::incrementCounter($thisIv, $inc, $config);
         /**
          * Perform the AES decryption. Decrypts the message.
          */
         $decrypted = \openssl_decrypt($read, $config->cipherMethod(), $ekey, OPENSSL_RAW_DATA, $thisIv);
         /**
          * Test for decryption faulure
          */
         if ($decrypted === false) {
             throw new Ex\CannotPerformOperationException('OpenSSL decryption error');
         }
         /**
          * Write the plaintext out to the output file
          */
         self::writeBytes($outputHandle, $decrypted, Core::ourStrlen($decrypted));
     }
     return true;
 }