/** * Test decryption */ public function testDecrypt() { $encryptedFile = $this->fileCrypt->encrypt($this->test_file, $this->test_encrypted_file); $this->fileCrypt->decrypt($encryptedFile, $this->test_decrypted_file); // Test if the decrypted file exists $this->assertTrue(file_exists($this->test_decrypted_file)); // Test if the checksum equals the original file $this->assertEquals($encryptedFile->getChecksum(), sha1_file($this->test_decrypted_file)); // Test if the decrypted file contains the same content as the original $this->assertEquals(file_get_contents($this->test_file), file_get_contents($this->test_decrypted_file)); // Test decryption of encrypted file with incorrect wrong IV try { $invalidEncryptedFile = EncryptedFile::create('2394qsf3-f9', $encryptedFile->getChecksum(), $encryptedFile->getPadding(), $encryptedFile->getFile()->getRealPath()); $this->fileCrypt->decrypt($invalidEncryptedFile, $this->test_decrypted_file); $this->fail('No exception was thrown on decrypting with an incorrect IV'); } catch (\Exception $e) { $this->assertInstanceOf(DecryptException::class, $e); } // Test decryption of encrypted file with incorrect checksum // We perform this test by setting the expected exception $this->setExpectedException(DecryptException::class); $invalidEncryptedFile = EncryptedFile::create($encryptedFile->getIV(), bin2hex(openssl_random_pseudo_bytes(16)), $encryptedFile->getPadding() * 2, $encryptedFile->getFile()->getRealPath()); $this->fileCrypt->decrypt($invalidEncryptedFile, $this->test_decrypted_file); }
/** * Encrypts a file and returns the checksum of the encrypted file. * You can use the checksum to verify integrity as this method of encryption (symmetrical) * doesn't allow for easy integrity verification. * * It's not required but highly recommended as an attacker can shift bytes and thus changes the data * on the encrypted file. * * @param string $source * @param string $target * @return EncryptedFile An encrypted file object containing information about the IV, checksum and padding * @throws EncryptException */ public function encrypt($source, $target) { $iv = mcrypt_create_iv($this->getIvSize(), $this->getRandomizer()); try { $this->encryptFile($source, $target, $iv); } catch (\Exception $e) { throw new EncryptException('Unable to encrypt file', 0, $e); } // Returns the encrypted file object, sets the padding and the source file checksum for later checking return EncryptedFile::create($iv, $this->calculateChecksum($source), $this->calculatePadding($source, $target), $target); }
/** * Asserts the testing of creating a file */ public function testCreate() { $this->assertInstanceOf(EncryptedFile::class, EncryptedFile::create(0, 0, 0, __FILE__)); $this->setExpectedException(\RuntimeException::class); EncryptedFile::create(0, 0, 0, 'non-existing_file.doc'); }