2
0

ZipPasswordTest.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of the nelexa/zip package.
  5. * (c) Ne-Lexa <https://github.com/Ne-Lexa/php-zip>
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. namespace PhpZip\Tests;
  10. use PhpZip\Constants\ZipCompressionMethod;
  11. use PhpZip\Constants\ZipEncryptionMethod;
  12. use PhpZip\Exception\InvalidArgumentException;
  13. use PhpZip\Exception\RuntimeException;
  14. use PhpZip\Exception\ZipAuthenticationException;
  15. use PhpZip\Exception\ZipEntryNotFoundException;
  16. use PhpZip\Exception\ZipException;
  17. use PhpZip\Model\ZipEntry;
  18. use PhpZip\ZipFile;
  19. /**
  20. * Tests with zip password.
  21. *
  22. * @internal
  23. *
  24. * @small
  25. */
  26. class ZipPasswordTest extends ZipFileSetTestCase
  27. {
  28. /**
  29. * Test archive password.
  30. *
  31. * @throws ZipException
  32. * @throws \Exception
  33. *
  34. * @noinspection PhpRedundantCatchClauseInspection
  35. */
  36. public function testSetPassword(): void
  37. {
  38. if (\PHP_INT_SIZE === 4) { // php 32 bit
  39. $this->expectException(RuntimeException::class);
  40. $this->expectExceptionMessage('Traditional PKWARE Encryption is not supported in 32-bit PHP.');
  41. }
  42. $password = base64_encode(random_bytes(100));
  43. $badPassword = 'bad password';
  44. // create encryption password with Traditional PKWARE encryption
  45. $zipFile = new ZipFile();
  46. $zipFile->addDir(__DIR__);
  47. $zipFile->setPassword($password, ZipEncryptionMethod::PKWARE);
  48. $zipFile->saveAsFile($this->outputFilename);
  49. $zipFile->close();
  50. static::assertCorrectZipArchive($this->outputFilename, $password);
  51. $zipFile->openFile($this->outputFilename);
  52. // check bad password for Traditional PKWARE encryption
  53. $zipFile->setReadPassword($badPassword);
  54. foreach ($zipFile->getListFiles() as $entryName) {
  55. try {
  56. $zipFile[$entryName];
  57. static::fail('Expected Exception has not been raised.');
  58. } catch (ZipException $e) {
  59. }
  60. }
  61. // check correct password for Traditional PKWARE encryption
  62. $zipFile->setReadPassword($password);
  63. foreach ($zipFile->getEntries() as $zipEntry) {
  64. static::assertTrue($zipEntry->isEncrypted());
  65. static::assertSame(ZipEncryptionMethod::getEncryptionMethodName($zipEntry->getEncryptionMethod()), 'Traditional PKWARE encryption');
  66. $decryptContent = $zipFile[$zipEntry->getName()];
  67. static::assertNotEmpty($decryptContent);
  68. static::assertStringContainsString('<?php', $decryptContent);
  69. }
  70. // change encryption method to WinZip Aes and update file
  71. $zipFile->setPassword($password/*, ZipEncryptionMethod::WINZIP_AES_256*/);
  72. $zipFile->saveAsFile($this->outputFilename);
  73. $zipFile->close();
  74. /** @see https://sourceforge.net/p/p7zip/discussion/383044/thread/c859a2f0/ WinZip 99-character limit */
  75. static::assertCorrectZipArchive($this->outputFilename, substr($password, 0, 99));
  76. // check from WinZip AES encryption
  77. $zipFile->openFile($this->outputFilename);
  78. // set bad password WinZip AES
  79. $zipFile->setReadPassword($badPassword);
  80. foreach ($zipFile->getListFiles() as $entryName) {
  81. try {
  82. $zipFile[$entryName];
  83. static::fail('Expected Exception has not been raised.');
  84. } catch (ZipAuthenticationException $ae) {
  85. static::assertNotNull($ae);
  86. }
  87. }
  88. // set correct password WinZip AES
  89. $zipFile->setReadPassword($password);
  90. foreach ($zipFile->getEntries() as $zipEntry) {
  91. static::assertTrue($zipEntry->isEncrypted());
  92. static::assertSame($zipEntry->getCompressionMethod(), ZipCompressionMethod::DEFLATED);
  93. static::assertSame(ZipEncryptionMethod::getEncryptionMethodName($zipEntry->getEncryptionMethod()), 'WinZip AES-256');
  94. $decryptContent = $zipFile[$zipEntry->getName()];
  95. static::assertNotEmpty($decryptContent);
  96. static::assertStringContainsString('<?php', $decryptContent);
  97. }
  98. // clear password
  99. $zipFile->addFromString('file1', '');
  100. $zipFile->disableEncryption();
  101. $zipFile->addFromString('file2', '');
  102. $zipFile->saveAsFile($this->outputFilename);
  103. $zipFile->close();
  104. static::assertCorrectZipArchive($this->outputFilename);
  105. // check remove password
  106. $zipFile->openFile($this->outputFilename);
  107. foreach ($zipFile->getEntries() as $zipEntry) {
  108. static::assertFalse($zipEntry->isEncrypted());
  109. }
  110. $zipFile->close();
  111. }
  112. /**
  113. * @throws ZipException
  114. * @throws \Exception
  115. */
  116. public function testTraditionalEncryption(): void
  117. {
  118. if (\PHP_INT_SIZE === 4) { // php 32 bit
  119. $this->expectException(RuntimeException::class);
  120. $this->expectExceptionMessage('Traditional PKWARE Encryption is not supported in 32-bit PHP.');
  121. }
  122. $password = md5(random_bytes(50));
  123. $zip = new ZipFile();
  124. $zip->addDirRecursive($this->outputDirname);
  125. $zip->setPassword($password, ZipEncryptionMethod::PKWARE);
  126. $zip->saveAsFile($this->outputFilename);
  127. $zip->close();
  128. static::assertCorrectZipArchive($this->outputFilename, $password);
  129. $zip->openFile($this->outputFilename);
  130. $zip->setReadPassword($password);
  131. static::assertFilesResult($zip, array_keys(self::$files));
  132. foreach ($zip->getEntries() as $zipEntry) {
  133. if (!$zipEntry->isDirectory()) {
  134. static::assertTrue($zipEntry->isEncrypted());
  135. static::assertSame(ZipEncryptionMethod::getEncryptionMethodName($zipEntry->getEncryptionMethod()), 'Traditional PKWARE encryption');
  136. }
  137. }
  138. $zip->close();
  139. }
  140. /**
  141. * @dataProvider winZipKeyStrengthProvider
  142. *
  143. * @throws ZipException
  144. * @throws \Exception
  145. */
  146. public function testWinZipAesEncryption(int $encryptionMethod, int $bitSize): void
  147. {
  148. $password = base64_encode(random_bytes(50));
  149. $zip = new ZipFile();
  150. $zip->addDirRecursive($this->outputDirname);
  151. $zip->setPassword($password, $encryptionMethod);
  152. $zip->saveAsFile($this->outputFilename);
  153. $zip->close();
  154. static::assertCorrectZipArchive($this->outputFilename, $password);
  155. $zip->openFile($this->outputFilename);
  156. $zip->setReadPassword($password);
  157. static::assertFilesResult($zip, array_keys(self::$files));
  158. foreach ($zip->getEntries() as $info) {
  159. if (!$info->isDirectory()) {
  160. static::assertTrue($info->isEncrypted());
  161. static::assertSame($info->getEncryptionMethod(), $encryptionMethod);
  162. static::assertSame(ZipEncryptionMethod::getEncryptionMethodName($info->getEncryptionMethod()), 'WinZip AES-' . $bitSize);
  163. }
  164. }
  165. $zip->close();
  166. }
  167. public function winZipKeyStrengthProvider(): array
  168. {
  169. return [
  170. [ZipEncryptionMethod::WINZIP_AES_128, 128],
  171. [ZipEncryptionMethod::WINZIP_AES_192, 192],
  172. [ZipEncryptionMethod::WINZIP_AES_256, 256],
  173. ];
  174. }
  175. /**
  176. * @throws ZipException
  177. */
  178. public function testEncryptionEntries(): void
  179. {
  180. if (\PHP_INT_SIZE === 4) { // php 32 bit
  181. $this->expectException(RuntimeException::class);
  182. $this->expectExceptionMessage('Traditional PKWARE Encryption is not supported in 32-bit PHP.');
  183. }
  184. $password1 = '353442434235424234';
  185. $password2 = 'adgerhvrwjhqqehtqhkbqrgewg';
  186. $zip = new ZipFile();
  187. $zip->addDir($this->outputDirname);
  188. $zip->setPasswordEntry('.hidden', $password1, ZipEncryptionMethod::PKWARE);
  189. $zip->setPasswordEntry('text file.txt', $password2, ZipEncryptionMethod::WINZIP_AES_256);
  190. $zip->saveAsFile($this->outputFilename);
  191. $zip->close();
  192. $zip->openFile($this->outputFilename);
  193. $zip->setReadPasswordEntry('.hidden', $password1);
  194. $zip->setReadPasswordEntry('text file.txt', $password2);
  195. static::assertFilesResult(
  196. $zip,
  197. [
  198. '.hidden',
  199. 'text file.txt',
  200. 'Текстовый документ.txt',
  201. 'empty dir/',
  202. 'LoremIpsum.txt',
  203. ]
  204. );
  205. $info = $zip->getEntry('.hidden');
  206. static::assertTrue($info->isEncrypted());
  207. static::assertSame(ZipEncryptionMethod::getEncryptionMethodName($info->getEncryptionMethod()), 'Traditional PKWARE encryption');
  208. $info = $zip->getEntry('text file.txt');
  209. static::assertTrue($info->isEncrypted());
  210. static::assertStringContainsString(
  211. 'WinZip AES',
  212. ZipEncryptionMethod::getEncryptionMethodName($info->getEncryptionMethod())
  213. );
  214. static::assertFalse($zip->getEntry('Текстовый документ.txt')->isEncrypted());
  215. static::assertFalse($zip->getEntry('empty dir/')->isEncrypted());
  216. $zip->close();
  217. }
  218. /**
  219. * @throws ZipException
  220. */
  221. public function testEncryptionEntriesWithDefaultPassword(): void
  222. {
  223. if (\PHP_INT_SIZE === 4) { // php 32 bit
  224. $this->expectException(RuntimeException::class);
  225. $this->expectExceptionMessage('Traditional PKWARE Encryption is not supported in 32-bit PHP.');
  226. }
  227. $password1 = '353442434235424234';
  228. $password2 = 'adgerhvrwjhqqehtqhkbqrgewg';
  229. $defaultPassword = ' f f f f f ffff f5 ';
  230. $zip = new ZipFile();
  231. $zip->addDir($this->outputDirname);
  232. $zip->setPassword($defaultPassword);
  233. $zip->setPasswordEntry('.hidden', $password1, ZipEncryptionMethod::PKWARE);
  234. $zip->setPasswordEntry('text file.txt', $password2, ZipEncryptionMethod::WINZIP_AES_256);
  235. $zip->saveAsFile($this->outputFilename);
  236. $zip->close();
  237. $zip->openFile($this->outputFilename);
  238. $zip->setReadPassword($defaultPassword);
  239. $zip->setReadPasswordEntry('.hidden', $password1);
  240. $zip->setReadPasswordEntry('text file.txt', $password2);
  241. static::assertFilesResult(
  242. $zip,
  243. [
  244. '.hidden',
  245. 'text file.txt',
  246. 'Текстовый документ.txt',
  247. 'empty dir/',
  248. 'LoremIpsum.txt',
  249. ]
  250. );
  251. $zipEntry = $zip->getEntry('.hidden');
  252. static::assertTrue($zipEntry->isEncrypted());
  253. static::assertSame(ZipEncryptionMethod::getEncryptionMethodName($zipEntry->getEncryptionMethod()), 'Traditional PKWARE encryption');
  254. $zipEntry = $zip->getEntry('text file.txt');
  255. static::assertTrue($zipEntry->isEncrypted());
  256. static::assertStringContainsString(
  257. 'WinZip AES',
  258. ZipEncryptionMethod::getEncryptionMethodName($zipEntry->getEncryptionMethod())
  259. );
  260. $zipEntry = $zip->getEntry('Текстовый документ.txt');
  261. static::assertTrue($zipEntry->isEncrypted());
  262. static::assertStringContainsString(
  263. 'WinZip AES',
  264. ZipEncryptionMethod::getEncryptionMethodName($zipEntry->getEncryptionMethod())
  265. );
  266. static::assertFalse($zip->getEntry('empty dir/')->isEncrypted());
  267. $zip->close();
  268. }
  269. /**
  270. * @throws ZipException
  271. */
  272. public function testSetEncryptionMethodInvalid(): void
  273. {
  274. $this->expectException(InvalidArgumentException::class);
  275. $this->expectExceptionMessage('Encryption method 9999 is not supported.');
  276. $zipFile = new ZipFile();
  277. $encryptionMethod = 9999;
  278. $zipFile['entry'] = 'content';
  279. $zipFile->setPassword('pass', $encryptionMethod);
  280. $zipFile->outputAsString();
  281. }
  282. /**
  283. * @throws ZipException
  284. */
  285. public function testEntryPassword(): void
  286. {
  287. $zipFile = new ZipFile();
  288. $zipFile->setPassword('pass');
  289. $zipFile['file'] = 'content';
  290. static::assertFalse($zipFile->getEntry('file')->isEncrypted());
  291. for ($i = 1; $i <= 10; $i++) {
  292. $entryName = 'file' . $i;
  293. $zipFile[$entryName] = 'content';
  294. if ($i < 6) {
  295. $zipFile->setPasswordEntry($entryName, 'pass');
  296. static::assertTrue($zipFile->getEntry($entryName)->isEncrypted());
  297. } else {
  298. static::assertFalse($zipFile->getEntry($entryName)->isEncrypted());
  299. }
  300. }
  301. $zipFile->disableEncryptionEntry('file3');
  302. static::assertFalse($zipFile->getEntry('file3')->isEncrypted());
  303. static::assertTrue($zipFile->getEntry('file2')->isEncrypted());
  304. $zipFile->disableEncryption();
  305. $zipEntries = $zipFile->getEntries();
  306. array_walk(
  307. $zipEntries,
  308. function (ZipEntry $zipEntry): void {
  309. $this->assertFalse($zipEntry->isEncrypted());
  310. }
  311. );
  312. $zipFile->close();
  313. }
  314. /**
  315. * @throws ZipException
  316. */
  317. public function testInvalidEncryptionMethodEntry(): void
  318. {
  319. $this->expectException(InvalidArgumentException::class);
  320. $this->expectExceptionMessage('Encryption method 99 is not supported.');
  321. $zipFile = new ZipFile();
  322. $zipFile->addFromString('file', 'content', ZipCompressionMethod::STORED);
  323. $zipFile->setPasswordEntry('file', 'pass', ZipCompressionMethod::WINZIP_AES);
  324. }
  325. /**
  326. * @throws ZipException
  327. */
  328. public function testArchivePasswordUpdateWithoutSetReadPassword(): void
  329. {
  330. $zipFile = new ZipFile();
  331. $zipFile['file1'] = 'content';
  332. $zipFile['file2'] = 'content';
  333. $zipFile['file3'] = 'content';
  334. $zipFile->setPassword('password');
  335. $zipFile->saveAsFile($this->outputFilename);
  336. $zipFile->close();
  337. static::assertCorrectZipArchive($this->outputFilename, 'password');
  338. $zipFile->openFile($this->outputFilename);
  339. static::assertCount(3, $zipFile);
  340. foreach ($zipFile->getEntries() as $zipEntry) {
  341. static::assertTrue($zipEntry->isEncrypted());
  342. }
  343. unset($zipFile['file3']);
  344. $zipFile['file4'] = 'content';
  345. $zipFile->rewrite();
  346. static::assertCorrectZipArchive($this->outputFilename, 'password');
  347. static::assertCount(3, $zipFile);
  348. static::assertFalse(isset($zipFile['file3']));
  349. static::assertTrue(isset($zipFile['file4']));
  350. static::assertTrue($zipFile->getEntry('file1')->isEncrypted());
  351. static::assertTrue($zipFile->getEntry('file2')->isEncrypted());
  352. static::assertFalse($zipFile->getEntry('file4')->isEncrypted());
  353. static::assertSame($zipFile['file4'], 'content');
  354. $zipFile->extractTo($this->outputDirname, ['file4']);
  355. static::assertFileExists($this->outputDirname . \DIRECTORY_SEPARATOR . 'file4');
  356. static::assertStringEqualsFile($this->outputDirname . \DIRECTORY_SEPARATOR . 'file4', $zipFile['file4']);
  357. $zipFile->close();
  358. }
  359. /**
  360. * @see https://github.com/Ne-Lexa/php-zip/issues/9
  361. *
  362. * @throws ZipException
  363. * @throws \Exception
  364. */
  365. public function testIssues9(): void
  366. {
  367. $contents = str_pad('', 1000, 'test;test2;test3' . \PHP_EOL);
  368. $password = base64_encode(random_bytes(20));
  369. $zipFile = new ZipFile();
  370. $zipFile
  371. ->addFromString('codes.csv', $contents, ZipCompressionMethod::DEFLATED)
  372. ->setPassword($password)
  373. ->saveAsFile($this->outputFilename)
  374. ->close()
  375. ;
  376. static::assertCorrectZipArchive($this->outputFilename, $password);
  377. $zipFile->openFile($this->outputFilename);
  378. $zipFile->setReadPassword($password);
  379. static::assertSame($zipFile['codes.csv'], $contents);
  380. $zipFile->close();
  381. }
  382. /**
  383. * @throws ZipEntryNotFoundException
  384. * @throws ZipException
  385. */
  386. public function testReadAesEncryptedAndRewriteArchive(): void
  387. {
  388. $file = __DIR__ . '/resources/aes_password_archive.zip';
  389. $password = '1234567890';
  390. $zipFile = new ZipFile();
  391. $zipFile->openFile($file);
  392. $zipFile->setReadPassword($password);
  393. $zipFile->setPassword($password);
  394. $zipFile->setEntryComment('contents.txt', 'comment'); // change entry, but not changed contents
  395. $zipFile->saveAsFile($this->outputFilename);
  396. $zipFile2 = new ZipFile();
  397. $zipFile2->openFile($this->outputFilename);
  398. $zipFile2->setReadPassword($password);
  399. static::assertSame($zipFile2->getListFiles(), $zipFile->getListFiles());
  400. foreach ($zipFile as $name => $contents) {
  401. static::assertNotEmpty($name);
  402. static::assertNotEmpty($contents);
  403. static::assertStringContainsString('test contents', $contents);
  404. static::assertSame($zipFile2[$name], $contents);
  405. }
  406. $zipFile2->close();
  407. $zipFile->close();
  408. }
  409. }