public void ProtectedTempZip() { FileInfo tmpFile = TempFile.CreateTempFile("protectedXlsx", ".zip"); FileInfo tikaProt = XSSFTestDataSamples.GetSampleFile("protected_passtika.xlsx"); FileInputStream fis = new FileInputStream(tikaProt.Open(FileMode.Open)); POIFSFileSystem poifs = new POIFSFileSystem(fis); EncryptionInfo ei = new EncryptionInfo(poifs); Decryptor dec = ei.Decryptor; bool passOk = dec.VerifyPassword("tika"); Assert.IsTrue(passOk); // generate session key SecureRandom sr = new SecureRandom(); byte[] ivBytes = new byte[16], keyBytes = new byte[16]; sr.NextBytes(ivBytes); sr.NextBytes(keyBytes); // extract encrypted ooxml file and write to custom encrypted zip file InputStream is1 = dec.GetDataStream(poifs); CopyToFile(is1, tmpFile, CipherAlgorithm.aes128, keyBytes, ivBytes); is1.Close(); // provide ZipEntrySource to poi which decrypts on the fly ZipEntrySource source = fileToSource(tmpFile, CipherAlgorithm.aes128, keyBytes, ivBytes); // test the source OPCPackage opc = OPCPackage.Open(source); String expected = "This is an Encrypted Excel spreadsheet."; //XSSFEventBasedExcelExtractor extractor = new XSSFEventBasedExcelExtractor(opc); //extractor.IncludeSheetNames = (/*setter*/false); //String txt = extractor.Text; //Assert.AreEqual(expected, txt.Trim()); //XSSFWorkbook wb = new XSSFWorkbook(opc); //txt = wb.GetSheetAt(0).GetRow(0).GetCell(0).StringCellValue; //Assert.AreEqual(expected, txt); //extractor.Close(); //wb.Close(); opc.Close(); source.Close(); poifs.Close(); fis.Close(); tmpFile.Delete(); throw new NotImplementedException(); }
private void InjectData(ZipEntrySource zipEntrySource, Stream outStream) { try { ZipOutputStream zos = new ZipOutputStream(outStream); try { var en = zipEntrySource.Entries; while (en.MoveNext()) { var ze = (ZipEntry)en.Current; zos.PutNextEntry(new ZipEntry(ze.Name)); var inputStream = zipEntrySource.GetInputStream(ze); XSSFSheet xSheet = GetSheetFromZipEntryName(ze.Name); if (xSheet != null) { SXSSFSheet sxSheet = GetSXSSFSheet(xSheet); var xis = sxSheet.getWorksheetXMLInputStream(); try { CopyStreamAndInjectWorksheet(inputStream, zos, xis); } finally { xis.Close(); } } else { CopyStream(inputStream, zos); } inputStream.Close(); } } finally { zos.Close(); } } finally { zipEntrySource.Close(); } }
/// <summary> /// Extract to a stream /// In other words, you can extract to a stream or to a directory (filesystem), but not both! /// The Password param is required for encrypted entries. /// </summary> void InternalExtractToStream(Stream outStream, string password, ZipContainer zipContainer, ZipEntrySource zipEntrySource, string fileName) { // workitem 7958 if (zipContainer == null) throw new BadStateException("This entry is an orphan"); // workitem 10355 if (zipContainer.ZipFile == null) throw new InvalidOperationException("Use Extract() only with ZipFile."); zipContainer.ZipFile.Reset(false); if (zipEntrySource != ZipEntrySource.ZipFile) throw new BadStateException("You must call ZipFile.Save before calling any Extract method"); OnBeforeExtract(this, null, zipContainer.ZipFile); _ioOperationCanceled = false; try { ValidateCompression(_CompressionMethod_FromZipFile, fileName, GetUnsupportedCompressionMethod(_CompressionMethod)); ValidateEncryption(Encryption, fileName, _UnsupportedAlgorithmId); if (IsDoneWithOutputToStream()) { WriteStatus("extract dir {0}...", null); // if true, then the entry was a directory and has been created. // We need to fire the Extract Event. OnAfterExtract(null); return; } // If no password explicitly specified, use the password on the entry itself, // or on the zipfile itself. if (_Encryption_FromZipFile != EncryptionAlgorithm.None) EnsurePassword(password); WriteStatus("extract entry {0} to stream...", fileName); var archiveStream = ArchiveStream; if (ExtractToStream(archiveStream, outStream, Encryption, _Crc32)) goto ExitTry; OnAfterExtract(null); ExitTry: ; } catch (Exception) { _ioOperationCanceled = true; throw; } }
/// <summary> /// Pass in either basedir or s, but not both. /// In other words, you can extract to a stream or to a directory (filesystem), but not both! /// The Password param is required for encrypted entries. /// </summary> void InternalExtractToBaseDir(string baseDir, string password, ZipContainer zipContainer, ZipEntrySource zipEntrySource, string fileName) { if (baseDir == null) throw new ArgumentNullException("baseDir"); // workitem 7958 if (zipContainer == null) throw new BadStateException("This entry is an orphan"); // workitem 10355 if (zipContainer.ZipFile == null) throw new InvalidOperationException("Use Extract() only with ZipFile."); zipContainer.ZipFile.Reset(false); if (zipEntrySource != ZipEntrySource.ZipFile) throw new BadStateException("You must call ZipFile.Save before calling any Extract method"); OnBeforeExtract(this, baseDir, zipContainer.ZipFile); _ioOperationCanceled = false; var fileExistsBeforeExtraction = false; var checkLaterForResetDirTimes = false; string targetFileName = null; try { ValidateCompression(_CompressionMethod_FromZipFile, fileName, GetUnsupportedCompressionMethod(_CompressionMethod)); ValidateEncryption(Encryption, fileName, _UnsupportedAlgorithmId); if (IsDoneWithOutputToBaseDir(baseDir, out targetFileName)) { WriteStatus("extract dir {0}...", targetFileName); // if true, then the entry was a directory and has been created. // We need to fire the Extract Event. OnAfterExtract(baseDir); return; } // workitem 10639 // do we want to extract to a regular filesystem file? // Check for extracting to a previously existing file. The user // can specify bejavior for that case: overwrite, don't // overwrite, and throw. Also, if the file exists prior to // extraction, it affects exception handling: whether to delete // the target of extraction or not. This check needs to be done // before the password check is done, because password check may // throw a BadPasswordException, which triggers the catch, // wherein the existing file may be deleted if not flagged as // pre-existing. if (File.Exists(targetFileName)) { fileExistsBeforeExtraction = true; int rc = CheckExtractExistingFile(baseDir, targetFileName); if (rc == 2) goto ExitTry; // cancel if (rc == 1) return; // do not overwrite } // If no password explicitly specified, use the password on the entry itself, // or on the zipfile itself. if (_Encryption_FromZipFile != EncryptionAlgorithm.None) EnsurePassword(password); // set up the output stream var tmpName = Path.GetRandomFileName(); var tmpPath = Path.Combine(Path.GetDirectoryName(targetFileName), tmpName); WriteStatus("extract file {0}...", targetFileName); using (var output = OpenFileStream(tmpPath, ref checkLaterForResetDirTimes)) { if (ExtractToStream(ArchiveStream, output, Encryption, _Crc32)) goto ExitTry; output.Close(); } MoveFileInPlace(fileExistsBeforeExtraction, targetFileName, tmpPath, checkLaterForResetDirTimes); OnAfterExtract(baseDir); ExitTry: ; } catch (Exception) { _ioOperationCanceled = true; throw; } finally { if (_ioOperationCanceled && targetFileName != null) { // An exception has occurred. If the file exists, check // to see if it existed before we tried extracting. If // it did not, attempt to remove the target file. There // is a small possibility that the existing file has // been extracted successfully, overwriting a previously // existing file, and an exception was thrown after that // but before final completion (setting times, etc). In // that case the file will remain, even though some // error occurred. Nothing to be done about it. if (File.Exists(targetFileName) && !fileExistsBeforeExtraction) File.Delete(targetFileName); } } }
private static ZipEntry Create(string nameInArchive, ZipEntrySource source, Object arg1, Object arg2) { if (String.IsNullOrEmpty(nameInArchive)) throw new Ionic.Zip.ZipException("The entry name must be non-null and non-empty."); ZipEntry entry = new ZipEntry(); // workitem 7071 // workitem 7926 - "version made by" OS should be zero for compat with WinZip entry._VersionMadeBy = (0 << 8) + 45; // indicates the attributes are FAT Attributes, and v4.5 of the spec entry._Source = source; entry._Mtime = entry._Atime = entry._Ctime = DateTime.UtcNow; if (source == ZipEntrySource.Stream) { entry._sourceStream = (arg1 as Stream); // may or may not be null } else if (source == ZipEntrySource.WriteDelegate) { entry._WriteDelegate = (arg1 as WriteDelegate); // may or may not be null } else if (source == ZipEntrySource.JitStream) { entry._OpenDelegate = (arg1 as OpenDelegate); // may or may not be null entry._CloseDelegate = (arg2 as CloseDelegate); // may or may not be null } else if (source == ZipEntrySource.ZipOutputStream) { } // workitem 9073 else if (source == ZipEntrySource.None) { // make this a valid value, for later. entry._Source = ZipEntrySource.FileSystem; } else { String filename = (arg1 as String); // must not be null if (String.IsNullOrEmpty(filename)) throw new Ionic.Zip.ZipException("The filename must be non-null and non-empty."); // The named file may or may not exist at this time. For example, when // adding a directory by name. We test existence when necessary: // when saving the ZipFile, or when getting the attributes, and so on. #if NETCF // workitem 6878 // Ionic.Zip.SharedUtilities.AdjustTime_Win32ToDotNet entry._Mtime = File.GetLastWriteTime(filename).ToUniversalTime(); entry._Ctime = File.GetCreationTime(filename).ToUniversalTime(); entry._Atime = File.GetLastAccessTime(filename).ToUniversalTime(); // workitem 7071 // can only get attributes of files that exist. if (File.Exists(filename) || Directory.Exists(filename)) entry._ExternalFileAttrs = (int)NetCfFile.GetAttributes(filename); #else // workitem 6878?? entry._Mtime = File.GetLastWriteTime(filename).ToUniversalTime(); entry._Ctime = File.GetCreationTime(filename).ToUniversalTime(); entry._Atime = File.GetLastAccessTime(filename).ToUniversalTime(); // workitem 7071 // can only get attributes on files that exist. if (File.Exists(filename) || Directory.Exists(filename)) entry._ExternalFileAttrs = (int)File.GetAttributes(filename); #endif entry._ntfsTimesAreSet = true; entry._LocalFileName = Path.GetFullPath(filename); // workitem 8813 } entry._LastModified = entry._Mtime; entry._FileNameInArchive = SharedUtilities.NormalizePathForUseInZipFile(nameInArchive); // We don't actually slurp in the file data until the caller invokes Write on this entry. return entry; }
private static ZipEntry Create(string nameInArchive, ZipEntrySource source, Object arg1, Object arg2) { if (String.IsNullOrEmpty(nameInArchive)) throw new Ionic.Zip.ZipException("The entry name must be non-null and non-empty."); ZipEntry entry = new ZipEntry(); // workitem 7071 // workitem 7926 - "version made by" OS should be zero for compat with WinZip entry._VersionMadeBy = (0 << 8) + 45; // indicates the attributes are FAT Attributes, and v4.5 of the spec entry._Source = source; entry._Mtime = entry._Atime = entry._Ctime = DateTime.UtcNow; if (source == ZipEntrySource.Stream) { entry._sourceStream = (arg1 as Stream); // may or may not be null } else if (source == ZipEntrySource.WriteDelegate) { entry._WriteDelegate = (arg1 as WriteDelegate); // may or may not be null } else if (source == ZipEntrySource.JitStream) { entry._OpenDelegate = (arg1 as OpenDelegate); // may or may not be null entry._CloseDelegate = (arg2 as CloseDelegate); // may or may not be null } else if (source == ZipEntrySource.ZipOutputStream) { } // workitem 9073 else if (source == ZipEntrySource.None) { // make this a valid value, for later. entry._Source = ZipEntrySource.Stream; } else { throw new ArgumentException("ZipEntrySource must be a valid value.", "source"); } entry._LastModified = entry._Mtime; entry._FileNameInArchive = SharedUtilities.NormalizePathForUseInZipFile(nameInArchive); // We don't actually slurp in the file data until the caller invokes Write on this entry. return entry; }
/** * Constructor. Opens a Zip based Open XML document from * a custom ZipEntrySource, typically an open archive * from another system * * @param zipEntry * Zip data to load. * @param access * The package access mode. */ public ZipPackage(ZipEntrySource zipEntry, PackageAccess access) : base(access) { this.zipArchive = zipEntry; }
private void InternalExtractToStream(Stream outStream, string password, ZipContainer zipContainer, ZipEntrySource zipEntrySource, string fileName) { // workitem 7958 if (zipContainer == null) throw new BadStateException("This entry is an orphan"); // workitem 10355 if (zipContainer.ZipFile == null) throw new InvalidOperationException("Use Extract() only with ZipFile."); if (zipEntrySource != ZipEntrySource.ZipFile) throw new BadStateException("You must call ZipFile.Save before calling any Extract method"); _ioOperationCanceled = false; try { ValidateCompression(_CompressionMethod_FromZipFile, fileName, GetUnsupportedCompressionMethod(_CompressionMethod)); ValidateEncryption(Encryption, fileName, _UnsupportedAlgorithmId); if (IsDoneWithOutputToStream()) { return; } // If no password explicitly specified, use the password on the entry itself, // or on the zipfile itself. if (_Encryption_FromZipFile != EncryptionAlgorithm.None) EnsurePassword(password); if (ExtractToStream(ArchiveStream, outStream, Encryption, _Crc32)) goto ExitTry; ExitTry: ; } catch (Exception) { _ioOperationCanceled = true; throw; } }
private void InternalExtractToStream(Stream outStream, string password, ZipContainer zipContainer, ZipEntrySource zipEntrySource, string fileName) { // workitem 7958 if (zipContainer == null) { throw new BadStateException("This entry is an orphan"); } // workitem 10355 if (zipContainer.ZipFile == null) { throw new InvalidOperationException("Use Extract() only with ZipFile."); } if (zipEntrySource != ZipEntrySource.ZipFile) { throw new BadStateException("You must call ZipFile.Save before calling any Extract method"); } _ioOperationCanceled = false; try { ValidateCompression(_CompressionMethod_FromZipFile, fileName, GetUnsupportedCompressionMethod(_CompressionMethod)); ValidateEncryption(Encryption, fileName, _UnsupportedAlgorithmId); if (IsDoneWithOutputToStream()) { return; } // If no password explicitly specified, use the password on the entry itself, // or on the zipfile itself. if (_Encryption_FromZipFile != EncryptionAlgorithm.None) { EnsurePassword(password); } if (ExtractToStream(ArchiveStream, outStream, Encryption, _Crc32)) { goto ExitTry; } ExitTry :; } catch (Exception) { _ioOperationCanceled = true; throw; } }
private static ZipEntry Create(string nameInArchive, ZipEntrySource source, Object arg1, Object arg2) { if (String.IsNullOrEmpty(nameInArchive)) { throw new Ionic.Zip.ZipException("The entry name must be non-null and non-empty."); } ZipEntry entry = new ZipEntry(); // workitem 7071 // workitem 7926 - "version made by" OS should be zero for compat with WinZip entry._VersionMadeBy = (0 << 8) + 45; // indicates the attributes are FAT Attributes, and v4.5 of the spec entry._Source = source; entry._Mtime = entry._Atime = entry._Ctime = DateTime.UtcNow; if (source == ZipEntrySource.Stream) { entry._sourceStream = (arg1 as Stream); // may or may not be null } else if (source == ZipEntrySource.WriteDelegate) { entry._WriteDelegate = (arg1 as WriteDelegate); // may or may not be null } else if (source == ZipEntrySource.JitStream) { entry._OpenDelegate = (arg1 as OpenDelegate); // may or may not be null entry._CloseDelegate = (arg2 as CloseDelegate); // may or may not be null } else if (source == ZipEntrySource.ZipOutputStream) { } // workitem 9073 else if (source == ZipEntrySource.None) { // make this a valid value, for later. entry._Source = ZipEntrySource.FileSystem; } else { String filename = (arg1 as String); // must not be null if (String.IsNullOrEmpty(filename)) { throw new Ionic.Zip.ZipException("The filename must be non-null and non-empty."); } try { // The named file may or may not exist at this time. For // example, when adding a directory by name. We test existence // when necessary: when saving the ZipFile, or when getting the // attributes, and so on. // workitem 6878?? entry._Mtime = File.GetLastWriteTime(filename).ToUniversalTime(); entry._Ctime = File.GetCreationTime(filename).ToUniversalTime(); entry._Atime = File.GetLastAccessTime(filename).ToUniversalTime(); // workitem 7071 // can only get attributes on files that exist. if (File.Exists(filename) || Directory.Exists(filename)) { entry._ExternalFileAttrs = (int)File.GetAttributes(filename); } entry._ntfsTimesAreSet = true; entry._LocalFileName = Path.GetFullPath(filename); // workitem 8813 } catch (System.IO.PathTooLongException ptle) { // workitem 14035 var msg = String.Format("The path is too long, filename={0}", filename); throw new ZipException(msg, ptle); } } entry._LastModified = entry._Mtime; entry._FileNameInArchive = SharedUtilities.NormalizePathForUseInZipFile(nameInArchive); // We don't actually slurp in the file data until the caller invokes Write on this entry. return(entry); }
/// <summary> /// Extract to a stream /// In other words, you can extract to a stream or to a directory (filesystem), but not both! /// The Password param is required for encrypted entries. /// </summary> void InternalExtractToStream(Stream outStream, string password, ZipContainer zipContainer, ZipEntrySource zipEntrySource, string fileName) { // workitem 10355 if (zipContainer.ZipFile == null) { throw new InvalidOperationException("Use Extract() only with ZipFile."); } zipContainer.ZipFile.Reset(false); if (zipEntrySource != ZipEntrySource.ZipFile) { throw new BadStateException("You must call ZipFile.Save before calling any Extract method"); } OnBeforeExtract(this, null, zipContainer.ZipFile); _ioOperationCanceled = false; try { ValidateCompression(_CompressionMethod_FromZipFile, fileName, GetUnsupportedCompressionMethod(_CompressionMethod)); ValidateEncryption(Encryption, fileName, _UnsupportedAlgorithmId); if (IsDoneWithOutputToStream()) { WriteStatus("extract dir {0}...", null); // if true, then the entry was a directory and has been created. // We need to fire the Extract Event. OnAfterExtract(null); return; } // If no password explicitly specified, use the password on the entry itself, // or on the zipfile itself. if (_Encryption_FromZipFile != EncryptionAlgorithm.None) { EnsurePassword(password); } WriteStatus("extract entry {0} to stream...", fileName); var archiveStream = ArchiveStream; if (ExtractToStream(archiveStream, outStream, Encryption, _Crc32)) { goto ExitTry; } OnAfterExtract(null); ExitTry :; } catch (Exception) { _ioOperationCanceled = true; throw; } }
/// <summary> /// Default constructor. /// </summary> /// <remarks> /// Applications should never need to call this directly. It is exposed to /// support COM Automation environments. /// </remarks> public ZipEntry() { _CompressionMethod = (Int16)CompressionMethod.Deflate; _Encryption = EncryptionAlgorithm.None; _Source = ZipEntrySource.None; #if !WINDOWS // See https://dotnetzip.codeplex.com/workitem/14049 AlternateEncoding = System.Text.Encoding.GetEncoding("UTF-8"); #else AlternateEncoding = System.Text.Encoding.GetEncoding("IBM437"); #endif AlternateEncodingUsage = ZipOption.Never; }