예제 #1
0
        private static ReaderProperties CreateReaderProperties(FileDecryptionProperties fileDecryptionProperties)
        {
            var readerProperties = ReaderProperties.GetDefaultReaderProperties();

            readerProperties.FileDecryptionProperties = fileDecryptionProperties;
            return(readerProperties);
        }
예제 #2
0
        private static void EncryptPdfWithPassword(string sourceFile, string passwordSource, string destinationFile, string passwordUser, string passwordOwner)
        {
            byte[] userPassword  = Encoding.ASCII.GetBytes(passwordUser);
            byte[] ownerPassword = Encoding.ASCII.GetBytes(passwordOwner);

            PdfReader reader = null;

            if (!string.IsNullOrEmpty(passwordSource))
            {
                byte[]           sourcePassword   = Encoding.ASCII.GetBytes(passwordSource);
                ReaderProperties readerProperties = new ReaderProperties().SetPassword(sourcePassword);
                reader = new PdfReader(sourceFile, readerProperties);
            }
            else
            {
                reader = new PdfReader(sourceFile);
            }

            WriterProperties props = new WriterProperties()
                                     .SetStandardEncryption(userPassword, ownerPassword, EncryptionConstants.ALLOW_PRINTING,
                                                            EncryptionConstants.ENCRYPTION_AES_256 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA);

            using PdfWriter writer = new PdfWriter(destinationFile, props);
            PdfDocument pdfDoc = null;

            try
            {
                pdfDoc = new PdfDocument(reader, writer);
            }
            finally
            {
                pdfDoc?.Close();
            }
        }
예제 #3
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
            HttpRequest req, ILogger log)
        {
            // Get the key from KeyVault using Key Vault References
            string password = System.Environment.GetEnvironmentVariable("PDFPassword");

            // Initialize properties
            var properties = new ReaderProperties();

            properties.SetPassword(Encoding.ASCII.GetBytes(password));

            // Now open the PDF
            using (var outputStream = new MemoryStream())
            {
                PdfDocument pdf = new PdfDocument(
                    new PdfReader(req.Body, properties),
                    new PdfWriter(outputStream));

                // Save the PDF with removed password
                pdf.Close();

                // Return the PDF to output
                return(new FileContentResult(outputStream.ToArray(), "application/pdf"));
            }
        }
예제 #4
0
        public static void CheckPDFPassword(FileObject file)
        {
            PdfDocument doc = null;

            try
            {
                var pdfReader = new PdfReader(file.FilePath);
                doc = new PdfDocument(pdfReader);
            }
            catch (iText.Kernel.PdfException e)
            {
                if (e.Message.Contains("password"))
                {
                    //openpopup to enter password
                    var readerProps = new ReaderProperties();
                    passwordDialogCommand.Execute(null);
                    var password = passwordDialogCommand.Password;
                    file.Password          = password;
                    file.PasswordProtected = true;
                    //call passwordinputcommand to get password popup.
                    readerProps.SetPassword(Encoding.ASCII.GetBytes(password));
                    var pdfReader = new PdfReader(file.FilePath, readerProps);
                    pdfReader.SetUnethicalReading(true);
                    doc = new PdfDocument(pdfReader);
                    pdfReader.Close();
                }
            }
            doc.Close();
        }
예제 #5
0
        public PdfDocument OpenRead(Stream stream, ReaderProperties readerProperties)
        {
            Check.NotNull(stream, nameof(stream), "stream is null");
            Check.NotNull(readerProperties, nameof(readerProperties), "readerProperties is null");

            var writer = new PdfReader(stream, readerProperties);

            return(new PdfDocument(writer));
        }
예제 #6
0
        public PdfDocument OpenRead(string filePath, ReaderProperties readerProperties)
        {
            CheckPath(filePath);
            Check.NotNull(readerProperties, nameof(readerProperties), "readerProperties is null");

            var writer = new PdfReader(filePath, readerProperties);

            return(new PdfDocument(writer));
        }
예제 #7
0
        /// <summary>
        /// Reads in the encrypted PDF with the supplied password to make sure it can be opened.
        /// </summary>
        private static void VerifyPdf(string pdfFile, string passwordUser)
        {
            byte[] userPassword = Encoding.ASCII.GetBytes(passwordUser);

            ReaderProperties readerProperties = new ReaderProperties().SetPassword(userPassword);

            using PdfReader reader = new PdfReader(pdfFile, readerProperties);
            PdfDocument pdfDocument = new PdfDocument(reader);
        }
예제 #8
0
        private static bool TryDecrypt(string encryptedPath, string decryptedFilePath, string password)
        {
            var readerProperties = new ReaderProperties().SetPassword(UTF8.GetBytes(password));

            using (var writer = new PdfWriter(decryptedFilePath))
                using (var reader = new PdfReader(encryptedPath, readerProperties))
                    using (var doc = new PdfDocument(reader, writer)) {
                        CheckExcedentPagesAndRemove(doc);
                        doc.Close();
                        reader.Close();
                    }
            return(true);
        }
예제 #9
0
        public void decompressionBombInsideMultipleStreamsTimingTest02()
        {
            MemoryLimitsAwareHandler memoryHandler = new MemoryLimitsAwareHandler();

            memoryHandler.SetMaxSizeOfSingleDecompressedPdfStream(int.MaxValue / 10 * 9);  // just to ensure that the multiple streams related exception is thrown
            memoryHandler.SetMaxSizeOfDecompressedPdfStreamsSum(1000000);

            ReaderProperties properties = new ReaderProperties();

            properties.SetMemoryLimitsAwareHandler(memoryHandler);

            PdfReader reader = new PdfReader(properties, TEST_RESOURCES_PATH + "acsploit_timing2.pdf");

            testDecompressionBomb(reader, MemoryLimitsAwareException.DuringDecompressionMultipleStreamsInSumOccupiedMoreMemoryThanAllowed);
        }
예제 #10
0
        public void decompressionBombInsideSingleStreamTest01()
        {
            MemoryLimitsAwareHandler memoryHandler = new MemoryLimitsAwareHandler();

            memoryHandler.SetMaxSizeOfSingleDecompressedPdfStream(5000000);
            memoryHandler.SetMaxSizeOfDecompressedPdfStreamsSum(1000000000000000000l); // just to ensure that the single stream related exception is thrown

            ReaderProperties properties = new ReaderProperties();

            properties.SetMemoryLimitsAwareHandler(memoryHandler);

            PdfReader reader = new PdfReader(properties, TEST_RESOURCES_PATH + "acsploit_output.pdf");

            testDecompressionBomb(reader, MemoryLimitsAwareException.DuringDecompressionSingleStreamOccupiedMoreMemoryThanAllowed);
        }
예제 #11
0
        /*************** UTILITY FUNCTIONS ***********************/

        private void SearchFiles(string folder_path)
        {
            /// CANNOT ACCESS UI THREAD
            /// CALLED FROM backgroundWorker1_DoWork()

            // for updating background worker
            float numFiles         = Directory.GetFiles(folder_path, "*.pdf", 0).Length;
            float numFilesSearched = 0;

            foreach (string full_file_path in Directory.EnumerateFiles(folder_path, "*.pdf"))
            {
                // LOGGING
                global_log_file_sw.Write(Path.GetFileNameWithoutExtension(full_file_path) + ": ");

                byte[]           passwordBytes    = Encoding.UTF8.GetBytes("real password goes here");
                ReaderProperties readerProperties = new ReaderProperties();
                readerProperties.SetPassword(passwordBytes);
                using (PdfReader reader = new PdfReader(full_file_path, readerProperties))
                    using (PdfDocument document = new PdfDocument(reader))
                    {
                        // flags
                        bool goodChart        = isGoodChart(document);
                        bool eight_zero_three = is803(document.GetFirstPage());

                        document.Close();
#if !DEBUG
                        if (!goodChart || eight_zero_three)
                        {
                            renameFile(full_file_path, goodChart, eight_zero_three);
                        }
#endif
                    }

                // update background worker progress
                numFilesSearched++;
                int percentComplete = (int)((numFilesSearched / numFiles) * 100);
                backgroundWorker1.ReportProgress(percentComplete);

                global_log_file_sw.Write(Environment.NewLine);
            }

            global_log_file_sw.Flush();
            global_log_file_sw.Close();
        }
예제 #12
0
        private void SignPdf(Job job)
        {
            if (!job.Profile.PdfSettings.Signature.Enabled)
            {
                return;
            }

            ReaderProperties readerProperties = new ReaderProperties();

            if (job.Profile.PdfSettings.Security.Enabled)
            {
                readerProperties.SetPassword(Encoding.Default.GetBytes(job.Passwords.PdfOwnerPassword));
            }

            var sourceFile = job.IntermediatePdfFile;
            var targetFile = AddTailToFile(sourceFile, "_processed");

            using (PdfReader pdfReader = new PdfReader(sourceFile, readerProperties))
                using (PdfWriter pdfWriter = new PdfWriter(targetFile))
                {
                    var signer = new PdfSigner(pdfReader, pdfWriter, new StampingProperties().PreserveEncryption().UseAppendMode());
                    using (signer.GetDocument())
                    {
                        try
                        {
                            new ITextSigner().SignPdfFile(signer, job.Profile, job.Passwords, job.Accounts);
                        }
                        catch (ProcessingException)
                        {
                            throw;
                        }
                        catch (Exception ex)
                        {
                            Logger.Warn($"Could not close iText pdf stamper.\r\n{ex}");
                        }
                    }
                }

            job.IntermediatePdfFile = targetFile;
            File.Delete(sourceFile);
        }
예제 #13
0
        public static int GetTotalPages(FileObject file)
        {
            PdfDocument doc = null;

            if (file.PasswordProtected)
            {
                var readerProps = new ReaderProperties();
                readerProps.SetPassword(Encoding.ASCII.GetBytes(file.Password));
                var pdfReader = new PdfReader(file.FilePath, readerProps);
                pdfReader.SetUnethicalReading(true);
                doc = new PdfDocument(pdfReader);
                pdfReader.Close();
            }
            else
            {
                var pdfReader = new PdfReader(file.FilePath);
                doc = new PdfDocument(pdfReader);
                pdfReader.Close();
            }
            int numPages = doc.GetNumberOfPages();

            doc.Close();
            return(numPages);
        }
예제 #14
0
        private async Task MergePDFs(MainViewModel viewModel)
        {
            viewModel.BuildStatus   = "Merging PDFs...";
            viewModel.BuildProgress = 0;

            bool overwriteFile = false;

            //Check if desired output file already exists
            if (File.Exists(Path.Combine(viewModel.WorkingDirectory, viewModel.OutputName + ".pdf")))
            {
                //ask user to overwrite file
                var result = MessageBox.Show("File exists, overwrite?", "Overwrite existing file", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.Cancel)
                {
                    return;
                }
                else
                {
                    overwriteFile = true;
                }
            }

            //Copy of real file list to manipulate
            List <FileObject> tempFileList = CopyFileObjectList(viewModel.Files);


            //create a temp directory to work in
            string outputPath = Path.Combine(viewModel.WorkingDirectory, "PDFTemp", viewModel.OutputName + ".pdf");

            Directory.CreateDirectory(Path.GetDirectoryName(outputPath));

            //copy all files to work in a temp directory.
            CopyTempFiles(viewModel, tempFileList, outputPath);

            PdfDocument pdf    = null;
            PdfMerger   merger = null;
            PdfDocument doc    = null;

            try
            {
                //check user option for encryption
                if (viewModel.Encrypt)
                {
                    pdf = new PdfDocument(new PdfWriter(outputPath, new WriterProperties()
                                                        .SetStandardEncryption(
                                                            Encoding.ASCII.GetBytes(viewModel.PDFPass),
                                                            null,
                                                            EncryptionConstants.ALLOW_PRINTING,
                                                            EncryptionConstants.ENCRYPTION_AES_256 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA)
                                                        ));
                }
                else
                {
                    pdf = new PdfDocument(new PdfWriter(outputPath));
                }
                merger = new PdfMerger(pdf);

                foreach (var file in tempFileList)
                {
                    if (!File.Exists(file.FilePath))
                    {
                        viewModel.BuildStatus = $"Failed: Temporary file({file.FileName}) no longer exists.";
                        pdf.Close();
                        merger.Close();
                        File.Delete(outputPath);
                        return;
                    }
                    try
                    {
                        //check if file is protected
                        if (file.PasswordProtected)
                        {
                            var readerProps = new ReaderProperties();
                            readerProps.SetPassword(Encoding.ASCII.GetBytes(file.Password));
                            var pdfReader = new PdfReader(file.FilePath, readerProps);
                            pdfReader.SetUnethicalReading(true);
                            doc = new PdfDocument(pdfReader);
                        }
                        else
                        {
                            var pdfReader = new PdfReader(file.FilePath);
                            doc = new PdfDocument(pdfReader);
                        }
                    }
                    catch (iText.Kernel.PdfException e)
                    {
                    }
                    //merge document
                    var numPages = doc.GetNumberOfPages();
                    merger.Merge(doc, 1, numPages);

                    doc.Close();

                    //update build progress
                    viewModel.BuildProgress += numPages;
                }
                pdf.Close();

                //move to orig location
                File.Move(outputPath, Path.Combine(viewModel.WorkingDirectory, viewModel.OutputName + ".pdf"), overwriteFile);

                //delete temp files
                foreach (var file in tempFileList)
                {
                    File.Delete(file.FilePath);
                }

                //delete temp dir
                Directory.Delete(Path.GetDirectoryName(outputPath));

                viewModel.BuildStatus = "Success: PDF Successfully Created";
            }
            //CLEAN UP THIS EXCEPTION GARBAGE EVENTUALLY
            catch (iText.IO.IOException e)
            {
                viewModel.BuildStatus = "Failed: Corrupt PDF";
            }
            //catch(iText.Signatures.)
            catch (iText.Kernel.PdfException e)
            {
                viewModel.BuildStatus = "Failed: Corrupt PDF";
            }
            catch (FileNotFoundException e)
            {
                viewModel.BuildStatus = "Failed: A PDF in the list no longer exists";
            }
            catch (IOException e)
            {
                viewModel.BuildStatus = "Failed: Attempting to modify a file in use";
            }
        }
예제 #15
0
        public static ParquetRowReader <TTuple> CreateRowReader <TTuple>(RandomAccessFile randomAccessFile, ReaderProperties readerProperties)
        {
            var fields       = GetFieldsAndProperties(typeof(TTuple));
            var readDelegate = GetOrCreateReadDelegate <TTuple>(fields);

            return(new ParquetRowReader <TTuple>(randomAccessFile, readerProperties, readDelegate, fields));
        }
예제 #16
0
        public static ParquetRowReader <TTuple> CreateRowReader <TTuple>(string path, ReaderProperties readerProperties)
        {
            var fields       = GetFieldsAndProperties(typeof(TTuple));
            var readDelegate = GetOrCreateReadDelegate <TTuple>(fields);

            return(new ParquetRowReader <TTuple>(path, readerProperties, readDelegate, fields));
        }