public void _Internal_Streams_ZipInput_Encryption(int fodderOption, int fileReadOption) { byte[] buffer = new byte[2048]; int n; int[] fileCounts = { 1, 2, _rnd.Next(8) + 6, _rnd.Next(18) + 16, _rnd.Next(48) + 56 }; for (int m = 0; m < fileCounts.Length; m++) { string password = TestUtilities.GenerateRandomPassword(); string dirToZip = String.Format("trial{0:D2}", m); if (!Directory.Exists(dirToZip)) Directory.CreateDirectory(dirToZip); int fileCount = fileCounts[m]; TestContext.WriteLine("====="); TestContext.WriteLine("Trial {0} filecount={1}", m, fileCount); var files = (new Func<string[]>( () => { if (fodderOption == 0) { // zero length files var a = new string[fileCount]; for (int i = 0; i < fileCount; i++) a[i] = CreateZeroLengthFile(i, dirToZip); return a; } if (fodderOption == 1) return TestUtilities.GenerateFilesFlat(dirToZip, fileCount, 100, 72000); // mixed = some zero and some not var b = new string[fileCount]; for (int i = 0; i < fileCount; i++) { if (_rnd.Next(3) == 0) b[i] = CreateZeroLengthFile(i, dirToZip); else { b[i] = Path.Combine(dirToZip, String.Format("nonzero{0:D4}.txt", i)); TestUtilities.CreateAndFillFileText(b[i], _rnd.Next(60000) + 100); } } return b; }))(); for (int i = 0; i < crypto.Length; i++) { EncryptionAlgorithm c = crypto[i]; string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("ZIS_Crypto.{0}.count.{1:D2}.{2}.zip", c.ToString(), fileCounts[m], fodderOption)); // Create the zip archive using (var zip = new ZipFile()) { zip.Password = password; zip.Encryption = c; if (fodderOption > 2) { zip.AddDirectoryByName("subdir"); zip.AddDirectory(dirToZip, "subdir"); } else zip.AddDirectory(dirToZip); zip.Save(zipFileToCreate); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), files.Length, "Incorrect number of entries in the zip file."); // extract the files string extractDir = String.Format("extract{0:D2}.{1:D2}", m, i); TestContext.WriteLine("Extract to: {0}", extractDir); Directory.CreateDirectory(extractDir); var input = (new Func<ZipInputStream>( () => { if (fileReadOption == 0) { var raw = File.OpenRead(zipFileToCreate); return new ZipInputStream(raw); } return new ZipInputStream(zipFileToCreate); }))(); using (input) { // set password if necessary if (crypto[i] != EncryptionAlgorithm.None) input.Password = password; ZipEntry e; while ((e = input.GetNextEntry()) != null) { TestContext.WriteLine("entry: {0}", e.FileName); string outputPath = Path.Combine(extractDir, e.FileName); if (e.IsDirectory) { // create the directory Directory.CreateDirectory(outputPath); } else { // emit the file using (var output = File.Create(outputPath)) { while ((n = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, n); } } } } } string[] filesUnzipped = (fodderOption > 2) ? Directory.GetFiles(Path.Combine(extractDir, "subdir")) : Directory.GetFiles(extractDir); // Verify the number of files extracted Assert.AreEqual<int>(files.Length, filesUnzipped.Length, "Incorrect number of files extracted. ({0}!={1})", files.Length, filesUnzipped.Length); } } }
public void Password_UnsetEncryptionAfterSetPassword_wi13909_ZF() { // Verify that unsetting the Encryption property after // setting a Password results in no encryption being used. // This method tests ZipFile. string unusedPassword = TestUtilities.GenerateRandomPassword(); int numTotalEntries = _rnd.Next(46)+653; string zipFileToCreate = "UnsetEncryption.zip"; using (var zip = new ZipFile()) { zip.Password = unusedPassword; zip.Encryption = EncryptionAlgorithm.None; for (int i=0; i < numTotalEntries; i++) { if (_rnd.Next(7)==0) { string entryName = String.Format("{0:D5}", i); zip.AddDirectoryByName(entryName); } else { string entryName = String.Format("{0:D5}.txt", i); if (_rnd.Next(12)==0) { var block = TestUtilities.GenerateRandomAsciiString() + " "; string contentBuffer = String.Format("This is the content for entry {0}", i); int n = _rnd.Next(6) + 2; for (int j=0; j < n; j++) contentBuffer += block; byte[] buffer = System.Text.Encoding.ASCII.GetBytes(contentBuffer); zip.AddEntry(entryName, contentBuffer); } else zip.AddEntry(entryName, Stream.Null); } } zip.Save(zipFileToCreate); } BasicVerifyZip(zipFileToCreate); }
public void Test_AddDirectoryByName_Nested() { Directory.SetCurrentDirectory(TopLevelDir); var dirsAdded = new System.Collections.Generic.List<String>(); string zipFileToCreate = Path.Combine(TopLevelDir, "Test_AddDirectoryByName_Nested.zip"); using (ZipFile zip1 = new ZipFile(zipFileToCreate)) { for (int n = 1; n <= 14; n++) { string DirName = n.ToString(); for (int i = 0; i < n; i++) { // create an arbitrary directory name, add it to the zip archive DirName = Path.Combine(DirName, TestUtilities.GenerateRandomAsciiString(11)); } zip1.AddDirectoryByName(DirName); dirsAdded.Add(DirName.Replace("\\", "/") + "/"); } zip1.Save(); } int dirCount = 0; using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { foreach (var e in zip2) { TestContext.WriteLine("dir: {0}", e.FileName); Assert.IsTrue(dirsAdded.Contains(e.FileName), "Cannot find the expected directory."); Assert.IsTrue(e.IsDirectory); dirCount++; } } Assert.AreEqual<int>(dirsAdded.Count, dirCount); }
public void Test_AddDirectoryByName_WithFiles() { Directory.SetCurrentDirectory(TopLevelDir); var dirsAdded = new System.Collections.Generic.List<String>(); string password = TestUtilities.GenerateRandomPassword(); string zipFileToCreate = Path.Combine(TopLevelDir, "Test_AddDirectoryByName_WithFiles.zip"); using (ZipFile zip1 = new ZipFile(zipFileToCreate)) { string dirName = null; int T = 3 + _rnd.Next(4); for (int n = 0; n < T; n++) { // nested directories dirName = (n == 0) ? "root" : Path.Combine(dirName, TestUtilities.GenerateRandomAsciiString(8)); zip1.AddDirectoryByName(dirName); dirsAdded.Add(dirName.Replace("\\", "/") + "/"); if (n % 2 == 0) zip1.Password = password; zip1.AddEntry(Path.Combine(dirName, new System.String((char)(n + 48), 3) + ".txt"), "Hello, Dolly!"); if (n % 2 == 0) zip1.Password = null; } zip1.Save(); } int entryCount = 0; using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { foreach (var e in zip2) { TestContext.WriteLine("e: {0}", e.FileName); if (e.IsDirectory) Assert.IsTrue(dirsAdded.Contains(e.FileName), "Cannot find the expected directory."); else { if ((entryCount - 1) % 4 == 0) e.Password = password; string output = StreamToStringUTF8(e.OpenReader()); Assert.AreEqual<string>("Hello, Dolly!", output); } entryCount++; } } Assert.AreEqual<int>(dirsAdded.Count * 2, entryCount); }
public void Test_AddDirectoryByName() { for (int n = 1; n <= 10; n++) { var dirsAdded = new System.Collections.Generic.List<String>(); string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("Test_AddDirectoryByName{0:N2}.zip", n)); using (ZipFile zip1 = new ZipFile()) { for (int i = 0; i < n; i++) { // create an arbitrary directory name, add it to the zip archive string dirName = TestUtilities.GenerateRandomName(24); zip1.AddDirectoryByName(dirName); dirsAdded.Add(dirName + "/"); } zip1.Save(zipFileToCreate); } int dirCount = 0; using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { foreach (var e in zip2) { TestContext.WriteLine("dir: {0}", e.FileName); Assert.IsTrue(dirsAdded.Contains(e.FileName), "Cannot find the expected entry"); Assert.IsTrue(e.IsDirectory); dirCount++; } } Assert.AreEqual<int>(n, dirCount); } }
public void ReadZip_DirectoryBitSetForEmptyDirectories() { string zipFileToCreate = Path.Combine(TopLevelDir, "ReadZip_DirectoryBitSetForEmptyDirectories.zip"); using (ZipFile zip1 = new ZipFile()) { zip1.AddDirectoryByName("Directory1"); // must retrieve with a trailing slash. ZipEntry e1 = zip1["Directory1/"]; Assert.AreNotEqual<ZipEntry>(null, e1); Assert.IsTrue(e1.IsDirectory, "The IsDirectory property was not set as expected."); zip1.AddDirectoryByName("Directory2"); zip1.AddEntry(Path.Combine("Directory2", "Readme.txt"), "This is the content"); Assert.IsTrue(zip1["Directory2/"].IsDirectory, "The IsDirectory property was not set as expected."); zip1.Save(zipFileToCreate); Assert.IsTrue(zip1["Directory1/"].IsDirectory, "The IsDirectory property was not set as expected."); } // read the zip and retrieve the dir entries again using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { Assert.IsTrue(zip2["Directory1/"].IsDirectory, "The IsDirectory property was not set as expected."); Assert.IsTrue(zip2["Directory2/"].IsDirectory, "The IsDirectory property was not set as expected."); } // now specify dir names with backslash using (ZipFile zip3 = ZipFile.Read(zipFileToCreate)) { Assert.IsTrue(zip3["Directory1\\"].IsDirectory, "The IsDirectory property was not set as expected."); Assert.IsTrue(zip3["Directory2\\"].IsDirectory, "The IsDirectory property was not set as expected."); Assert.IsNull(zip3["Directory1"]); Assert.IsNull(zip3["Directory2"]); } }
public void Extended_CheckZip2() { string textToEncode = "Pay no attention to this: " + "We've read in the regular entry header, the extra field, and any " + "encryption header. The pointer in the file is now at the start of " + "the filedata, which is potentially compressed and encrypted. Just " + "ahead in the file, there are _CompressedFileDataSize bytes of " + "data, followed by potentially a non-zero length trailer, " + "consisting of optionally, some encryption stuff (10 byte MAC for " + "AES), and then the bit-3 trailer (16 or 24 bytes). " + " " + "The encryption can be either PKZIP 2.0 (weak) encryption, or " + "WinZip-compatible AES encryption, which is considered to be " + "strong and for that reason is preferred. In the WinZip AES " + "option, there are two different keystrengths supported: 128 bits " + "and 256 bits. " + " " + "The extra field, which I mentioned previously, specifies " + "additional metadata about the entry, which is strictly-speaking, " + "optional. These data are things like high-resolution timestamps, " + "data sizes that exceed 2^^32, and other encryption " + "possibilities. In each case the library that reads a zip file " + "needs to be able to correctly deal with the various fields, " + "validating the values within them. " + " " + "Now, cross all that with the variety of usage patterns - creating a " + "zip, or reading, or extracting, or updating, or updating several " + "times. And also, remember that the metadata may change during " + "updates: an application can apply a password where none was used " + "previously, or it may wish to remove an entry from the zip entirely. " + " " + "The huge variety of combinations of possibilities is what makes " + "testing a zip library so challenging. " ; string testBin = TestUtilities.GetTestBinDir(CurrentDir); string fileToZip = Path.Combine(testBin, "Ionic.Zip.dll"); for (int i = 0; i < crypto.Length; i++) { for (int j = 0; j < z64.Length; j++) { string zipFile = String.Format("Extended-CheckZip2-{0}.{1}.zip", i, j); string password = Path.GetRandomFileName(); TestContext.WriteLine("================================="); TestContext.WriteLine("Creating {0}...", Path.GetFileName(zipFile)); string dir = Path.GetRandomFileName(); using (var zip = new ZipFile()) { zip.Comment = String.Format("Encryption={0} Zip64={1} pw={2}", crypto[i].ToString(), z64[j].ToString(), password); zip.Encryption = crypto[i]; if (crypto[i] != EncryptionAlgorithm.None) { TestContext.WriteLine("Encryption({0}) Zip64({1}) pw({2})", crypto[i].ToString(), z64[j].ToString(), password); zip.Password = password; } else TestContext.WriteLine("Encryption({0}) Zip64({1})", crypto[i].ToString(), z64[j].ToString()); zip.UseZip64WhenSaving = z64[j]; int N = _rnd.Next(11) + 5; for (int k = 0; k < N; k++) zip.AddDirectoryByName(Path.GetRandomFileName()); zip.AddEntry("File1.txt", textToEncode); zip.AddFile(fileToZip, Path.GetRandomFileName()); zip.Save(zipFile); } BasicVerifyZip(zipFile, password, false); TestContext.WriteLine("Checking zip..."); using (var sw = new StringWriter()) { bool result = ZipFile.CheckZip(zipFile, false, sw); Assert.IsTrue(result, "Zip ({0}) does not check OK", zipFile); var msgs = sw.ToString().Split('\n'); foreach (var msg in msgs) TestContext.WriteLine("{0}", msg); } TestContext.WriteLine("OK"); TestContext.WriteLine(""); } } }
public void Extended_CheckZip1() { string[] dirNames = { "", Path.GetFileName(Path.GetRandomFileName()) }; string textToEncode = "Pay no attention to this: " + "We've read in the regular entry header, the extra field, and any " + "encryption header. The pointer in the file is now at the start of " + "the filedata, which is potentially compressed and encrypted. Just " + "ahead in the file, there are _CompressedFileDataSize bytes of data, " + "followed by potentially a non-zero length trailer, consisting of " + "optionally, some encryption stuff (10 byte MAC for AES), " + "and then the bit-3 trailer (16 or 24 bytes). "; for (int i = 0; i < crypto.Length; i++) { for (int j = 0; j < z64.Length; j++) { for (int k = 0; k < dirNames.Length; k++) { string zipFile = String.Format("Extended-CheckZip1-{0}.{1}.{2}.zip", i, j, k); string password = Path.GetRandomFileName(); TestContext.WriteLine("================================="); TestContext.WriteLine("Creating {0}...", Path.GetFileName(zipFile)); using (var zip = new ZipFile()) { zip.Comment = String.Format("Encryption={0} Zip64={1} pw={2}", crypto[i].ToString(), z64[j].ToString(), password); if (crypto[i] != EncryptionAlgorithm.None) { TestContext.WriteLine("Encryption({0}) Zip64({1}) pw({2})", crypto[i].ToString(), z64[j].ToString(), password); zip.Encryption = crypto[i]; zip.Password = password; } else TestContext.WriteLine("Encryption({0}) Zip64({1})", crypto[i].ToString(), z64[j].ToString()); zip.UseZip64WhenSaving = z64[j]; if (!String.IsNullOrEmpty(dirNames[k])) zip.AddDirectoryByName(dirNames[k]); zip.AddEntry(Path.Combine(dirNames[k], "File1.txt"), textToEncode); zip.Save(zipFile); } BasicVerifyZip(zipFile, password); TestContext.WriteLine("Checking zip..."); using (var sw = new StringWriter()) { bool result = ZipFile.CheckZip(zipFile, false, sw); Assert.IsTrue(result, "Zip ({0}) does not check OK", zipFile); var msgs = sw.ToString().Split('\n'); foreach (var msg in msgs) TestContext.WriteLine("{0}", msg); } } } } }
public void Unicode_AddDirectoryByName_wi8984() { string format = "弹出应用程序{0:D3}.dir"; // Chinese characters System.Text.Encoding UTF8 = System.Text.Encoding.GetEncoding("UTF-8"); TestContext.WriteLine("== WorkItem 8984"); // three trials: one for old-style // ProvisionalAlternateEncoding, one for "AsNecessary" // and one for "Always" for (int j=0; j < 3; j++) { TestContext.WriteLine("Trial {0}", j); for (int n = 1; n <= 10; n++) { TestContext.WriteLine("nEntries {0}", n); var dirsAdded = new System.Collections.Generic.List<String>(); var zipFileToCreate = String.Format("wi8984-{0}-{1:N2}.zip", j, n); using (ZipFile zip1 = new ZipFile(zipFileToCreate)) { switch (j) { case 0: #pragma warning disable 618 zip1.UseUnicodeAsNecessary = true; #pragma warning restore 618 break; case 1: zip1.AlternateEncoding = UTF8; zip1.AlternateEncodingUsage = ZipOption.AsNecessary; break; case 2: zip1.AlternateEncoding = UTF8; zip1.AlternateEncodingUsage = ZipOption.Always; break; } for (int i = 0; i < n; i++) { // create an arbitrary directory name, add it to the zip archive string dirName = String.Format(format, i); zip1.AddDirectoryByName(dirName); dirsAdded.Add(dirName + "/"); } zip1.Save(); } string extractDir = String.Format("extract-{0}-{1:D3}", j, n); int dirCount = 0; using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { foreach (var e in zip2) { TestContext.WriteLine("dir: {0}", e.FileName); Assert.IsTrue(dirsAdded.Contains(e.FileName), "Cannot find the expected entry ({0})", e.FileName); Assert.IsTrue(e.IsDirectory); e.Extract(extractDir); dirCount++; } } Assert.AreEqual<int>(n, dirCount); TestContext.WriteLine(""); } TestContext.WriteLine(""); } }