예제 #1
0
        internal void SetEncryption(WriterProperties writerProperties, ConversionProfile profile, JobPasswords jobPasswords)
        {
            if (!profile.PdfSettings.Security.Enabled)
            {
                return;
            }

            var encryption = CalculatePermissionValue(profile);

            _logger.Debug("Calculated Permission Value: " + encryption);

            if (string.IsNullOrEmpty(jobPasswords.PdfOwnerPassword))
            {
                _logger.Error("Launched encryption without owner password.");
                throw new ProcessingException("Launched encryption without owner password.", ErrorCode.Encryption_NoOwnerPassword);
            }

            var ownerPassword = Encoding.Default.GetBytes(jobPasswords.PdfOwnerPassword);

            byte[] userPassword = null;

            if (profile.PdfSettings.Security.RequireUserPassword)
            {
                if (string.IsNullOrEmpty(jobPasswords.PdfUserPassword))
                {
                    _logger.Error("Launched encryption without user password.");
                    throw new ProcessingException("Launched encryption without user password.", ErrorCode.Encryption_NoUserPassword);
                }
                userPassword = Encoding.Default.GetBytes(jobPasswords.PdfUserPassword);
            }

            switch (profile.PdfSettings.Security.EncryptionLevel)
            {
            case EncryptionLevel.Rc40Bit:
                writerProperties.SetStandardEncryption(userPassword, ownerPassword,
                                                       encryption, EncryptionConstants.STANDARD_ENCRYPTION_40);
                break;

            case EncryptionLevel.Rc128Bit:
                writerProperties.SetStandardEncryption(userPassword, ownerPassword,
                                                       encryption, EncryptionConstants.STANDARD_ENCRYPTION_128);
                break;

            case EncryptionLevel.Aes128Bit:
            case EncryptionLevel.Aes256Bit:
                writerProperties.SetStandardEncryption(userPassword, ownerPassword,
                                                       encryption, EncryptionConstants.ENCRYPTION_AES_128);
                break;
            }
        }
예제 #2
0
        public void EncryptiText()
        {
            string password      = "******";
            string inPdf         = "Skyhigh-Secure-Datasheet-0214.pdf";
            string sourcePdfFile = Path.Combine(this.pdfRessources, inPdf);
            // Set source and target folders
            string targetFolder = outDir;
            var    method       = System.Reflection.MethodBase.GetCurrentMethod().Name;
            string targetFile   = Path.Combine(targetFolder, string.Concat(DateTime.Now.ToString("yyyyMMdd"), "_" + method + "_encrypted.pdf"));

            Assert.IsTrue(File.Exists(sourcePdfFile), "Source file doesn't exist");

            if (File.Exists(targetFile))
            {
                File.Delete(targetFile);
            }
            Assert.IsFalse(File.Exists(targetFile));

            byte[] passwordBytes = Encoding.ASCII.GetBytes(password);

            WriterProperties propComp = new WriterProperties();

            propComp.SetFullCompressionMode(false);
            propComp.SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            propComp.SetStandardEncryption(passwordBytes, passwordBytes, 0, EncryptionConstants.ENCRYPTION_AES_256 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA);
            PdfWriter   theCompWriter = new PdfWriter(targetFile, propComp);
            PdfDocument origPdf       = new PdfDocument(new PdfReader(sourcePdfFile), theCompWriter);

            Assert.IsNotNull(origPdf);
            origPdf.Close();
            Assert.IsTrue(new FileInfo(sourcePdfFile).Length < new FileInfo(targetFile).Length, "target file is not bigger than the source file");

            //check out http://itextsupport.com/apidocs/itext7/latest/com/itextpdf/kernel/pdf/PdfEncryptedPayloadDocument.html
        }
예제 #3
0
        static void Main(string[] args)
        {
            var cl = new CommandLine(true);

            cl.DefineOption("input", "Input File", true, false);
            cl.DefineOption("pw", "Password", true, false);

            var suc = cl.LoadArguments(args);

            if (suc)
            {
                string inputFile = cl.GetOptionValue("input")[0];
                string password  = cl.GetOptionValue("pw")[0];


                // Code below copied from https://itextpdf.com/en/demos/protect-pdf-files-free-online
                string OutputFolder = Path.GetDirectoryName(inputFile);
                byte[] USERPASS     = System.Text.Encoding.Default.GetBytes(password);
                byte[] OWNERPASS    = System.Text.Encoding.Default.GetBytes(password);

                PdfReader pdfReader = new PdfReader(inputFile);

                WriterProperties writerProperties = new WriterProperties();
                writerProperties.SetStandardEncryption(USERPASS, OWNERPASS, EncryptionConstants.ALLOW_PRINTING, EncryptionConstants.ENCRYPTION_AES_128);

                string      outputFile  = Path.Combine(OutputFolder, Path.GetFileNameWithoutExtension(inputFile) + "_Protected.pdf");
                PdfWriter   pdfWriter   = new PdfWriter(new FileStream(outputFile, FileMode.Create), writerProperties);
                PdfDocument pdfDocument = new PdfDocument(pdfReader, pdfWriter);
                pdfDocument.Close();

                Console.WriteLine("Create file: " + outputFile);
            }
        }
예제 #4
0
        /// <summary>
        /// Encrypts a file with AES-256 using the given owner password. The user password is equal to the owner password. Owner and user are granted all permission.
        /// </summary>
        /// <param name="ownerPassword"></param>
        public void ExportFileEncrypted(string ownerPassword)
        {
            int permissions = 4096 - 3; // all permissions, @see EncryptionConstants

            byte[]           rawOwnerPassword = new System.Text.ASCIIEncoding().GetBytes(ownerPassword);
            WriterProperties writerProperties = new WriterProperties();

            writerProperties.SetStandardEncryption(rawOwnerPassword, rawOwnerPassword, permissions, EncryptionConstants.ENCRYPTION_AES_256);
            PdfWriter outputWriter = new PdfWriter(outputStream, writerProperties);

            ExportOperation(outputWriter);
        }
예제 #5
0
        private bool createiText7Pdf(string password = null)
        {
            bool success = false;

            log.Info($"Using iText7 library to create a package with format [{this.packerType}]");
            if (this.overwrite)
            {
                deleteIfExist(this.dstFileName);
            }

            try
            {
                Stream stream = getTemplatePdfStream();
                if (stream == null)
                {
                    log.Error("Could not read the PDF Template from stream");
                    throw new FileNotFoundException("Could not read the PDF template");
                }

                WriterProperties propComp = new WriterProperties();
                propComp.SetFullCompressionMode(true);
                propComp.SetCompressionLevel(CompressionConstants.BEST_COMPRESSION);
                if (String.IsNullOrEmpty(password))
                {
                    log.Warn($"No password was supplied, so the output file will be unencrypted [{this.dstFileName}]");
                }
                else
                {
                    byte[] passwordBytes = Encoding.ASCII.GetBytes(password);
                    propComp.SetStandardEncryption(passwordBytes, passwordBytes, 0, EncryptionConstants.ENCRYPTION_AES_256 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA);
                    log.Info("Enabled PDF AES_256 encryption");
                }
                PdfWriter   theCompWriter = new PdfWriter(this.dstFileName, propComp);
                PdfDocument newPdf        = new PdfDocument(new PdfReader(stream), theCompWriter);
                foreach (string file in this.srcFileList)
                {
                    string      filename = Path.GetFileName(file);
                    PdfFileSpec fileSpec = PdfFileSpec.CreateEmbeddedFileSpec(
                        newPdf, File.ReadAllBytes(file), filename, filename, null, null, null);
                    newPdf.AddFileAttachment(filename, fileSpec);
                    log.Debug($"Added file '{filename}' as attachment to pdf");
                }
                newPdf.Close();
            }
            catch (Exception e)
            {
                log.Error($"Exception while trying to pack with iText7", e);
                return(false);
            }
            log.Info($"Successfully packed the files into [{this.dstFileName}]");
            return(success);
        }
예제 #6
0
        public static void EncryptPdf(string password)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                PdfReader        pdfReader        = new PdfReader(new MemoryStream(PdfFile));
                byte[]           ownerPassword    = System.Text.Encoding.Default.GetBytes(password);
                WriterProperties writerProperties = new WriterProperties();
                writerProperties.SetStandardEncryption(ownerPassword, ownerPassword, EncryptionConstants.ALLOW_PRINTING, EncryptionConstants.ENCRYPTION_AES_256);

                PdfWriter   pdfWriter   = new PdfWriter(stream, writerProperties);
                PdfDocument pdfDocument = new PdfDocument(pdfReader, pdfWriter);

                pdfDocument.Close();
                pdfReader.Close();
                pdfWriter.Close();

                FinalEncryptedPdfURL = Format + Convert.ToBase64String(stream.ToArray());
            }

            IsSubmitComplete     = true;
            IsEncryptionComplete = true;
        }
예제 #7
0
        private void btnEncrypt_Click(object sender, EventArgs e)
        {
            // Clean up text
            txtInputFile.Text  = txtInputFile.Text.Trim();
            txtOutputFile.Text = txtOutputFile.Text.Trim();

            // Ensure input and output are not the same.
            if (txtInputFile.Text.ToLower() == txtOutputFile.Text.ToLower())
            {
                MessageBox.Show("Source and Destination files cannot be the same.", "Invalid source/destination", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtOutputFile.Focus();
                txtOutputFile.SelectAll();
                return;
            }

            // Ensure input file exists.
            if (!File.Exists(txtInputFile.Text))
            {
                MessageBox.Show("Source file does not exist.");
                txtInputFile.Focus();
                txtInputFile.SelectAll();
                return;
            }

            // If output file exists, prompt to overwrite.
            if (File.Exists(txtOutputFile.Text))
            {
                if (MessageBox.Show("Destination file already exists.  Overwrite this file?", "Overwrite file?", MessageBoxButtons.YesNo) != DialogResult.Yes)
                {
                    txtOutputFile.Focus();
                    txtOutputFile.SelectAll();
                    return;
                }
            }

            // Verify password:
            if (txtPassword.Text == "")
            {
                MessageBox.Show("No password specified.");
                txtPassword.Focus();
                return;
            }

            // Confirm password:
            if (Settings.password_confirm)
            {
                var input = new frmInputBox();
                input.prompt = "Please retype the password to confirm.";
                input.title  = "Confirm password";
                input.ShowDialog();                     // Modal, blocking call

                if (input.cancelled)
                {
                    return;
                }

                // If password doesn't match, stop.
                if (input.result != txtPassword.Text)
                {
                    MessageBox.Show("Password does not match. Please retry.");
                    return;
                }
            }

            // See https://itextpdf.com/en/resources/faq/technical-support/itext-7/how-protect-already-existing-pdf-password
            try
            {
                // Set mouse cursor to wait.
                Cursor.Current = Cursors.WaitCursor;
                Application.DoEvents();

                // Encryption properties:
                int encryption_properties = (int)Settings.encryption_type;

                // If specified, disable encrypting metadata.
                if (!Settings.encrypt_metadata)
                {
                    encryption_properties |= EncryptionConstants.DO_NOT_ENCRYPT_METADATA;
                }

                // Set document options
                int document_options = 0;
                if (Settings.allow_printing)
                {
                    document_options |= EncryptionConstants.ALLOW_PRINTING;
                }
                if (Settings.allow_degraded_printing)
                {
                    document_options |= EncryptionConstants.ALLOW_DEGRADED_PRINTING;
                }
                if (Settings.allow_modifying)
                {
                    document_options |= EncryptionConstants.ALLOW_MODIFY_CONTENTS;
                }
                if (Settings.allow_modifying_annotations)
                {
                    document_options |= EncryptionConstants.ALLOW_MODIFY_ANNOTATIONS;
                }
                if (Settings.allow_copying)
                {
                    document_options |= EncryptionConstants.ALLOW_COPY;
                }
                if (Settings.allow_form_fill)
                {
                    document_options |= EncryptionConstants.ALLOW_FILL_IN;
                }
                if (Settings.allow_assembly)
                {
                    document_options |= EncryptionConstants.ALLOW_ASSEMBLY;
                }
                if (Settings.allow_screenreaders)
                {
                    document_options |= EncryptionConstants.ALLOW_SCREENREADERS;
                }

                PdfReader        reader = new PdfReader(txtInputFile.Text);                                                           // Create a PdfReader with the input file.
                WriterProperties prop   = new WriterProperties();                                                                     // Set properties of output
                prop.SetStandardEncryption(Encoding.ASCII.GetBytes(txtPassword.Text), null, document_options, encryption_properties); // Enable encryption
                // Setting Owner Password to null generates random password.

                PdfWriter   writer = new PdfWriter(txtOutputFile.Text, prop); // Set up the output file
                PdfDocument pdf    = new PdfDocument(reader, writer);         // Create the new document
                pdf.Close();                                                  // Close the output document.
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred while processing the file: " + ex.Message);
                Cursor.Current = Cursors.Default;
                return;
            }

            // If launching a program:
            if (Settings.run_after)
            {
                // Attempt to run the program, passing the newly encrypted filename.
                Process.Start(Settings.run_after_file, txtOutputFile.Text);
            }

            // If opening the output file:
            if (Settings.open_after)
            {
                // Attempt to launch the default app for the file.
                Process.Start(txtOutputFile.Text);
            }

            // If launching Explorer:
            if (Settings.show_folder_after)
            {
                // Attempt to launch the folder with the file highlighted.
                Process.Start("explorer.exe", "/select," + txtOutputFile.Text);
            }

            // If closing after encryption
            if (Settings.close_after)
            {
                this.Close();
            }

            Cursor.Current = Cursors.Default;                   // Return to default cursor.
        }
예제 #8
0
        private void btnPDF_Click(object sender, EventArgs e)
        {
            // Source File
            string sourceFile = txtFilePath.Text;
            // New filename
            string newNonSecureFile = sourceFile.Substring(0, sourceFile.Length - 4) + " - Non-Secure.pdf";
            // New secure file
            string newSecureFile = sourceFile.Substring(0, sourceFile.Length - 4) + " - Secure.pdf";

            //Initialize PDF document
            PdfDocument pdfDoc   = new PdfDocument(new PdfReader(sourceFile), new PdfWriter(newNonSecureFile));
            Document    document = new Document(pdfDoc);
            Rectangle   pageSize;
            int         n = pdfDoc.GetNumberOfPages();

            for (int i = 1; i <= n; i++)
            {
                PdfPage page = pdfDoc.GetPage(i);
                pageSize = page.GetPageSize();
                //Draw watermark
                Paragraph paragraph = new Paragraph(txtWatermark.Text).SetFontSize(30);
                PdfCanvas over      = new PdfCanvas(pdfDoc.GetPage(i).NewContentStreamBefore(), new PdfResources(), pdfDoc);

                // Watermark color selection
                if (rbRed.Checked == true)
                {
                    over.SetFillColor(ColorConstants.RED);
                }
                else if (rbOrange.Checked == true)
                {
                    over.SetFillColor(ColorConstants.ORANGE);
                }
                else if (rbBlue.Checked == true)
                {
                    over.SetFillColor(ColorConstants.BLUE);
                }
                else if (rbBlack.Checked == true)
                {
                    over.SetFillColor(ColorConstants.BLACK);
                }
                else
                {
                    over.SetFillColor(ColorConstants.MAGENTA);
                }
                over.SaveState();
                Canvas canvasWatermark1 = new Canvas(over, pdfDoc.GetDefaultPageSize())
                                          .ShowTextAligned(paragraph, pageSize.GetWidth() / 2, pageSize.GetHeight() / 2, pdfDoc.GetPageNumber(page), TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);
                canvasWatermark1.Close();

                // Creating a dictionary that maps resource names to graphics state parameter dictionaries

                PdfExtGState gs1 = new PdfExtGState().SetFillOpacity(0.2f);
                over.SetExtGState(gs1);
                over.RestoreState();
            }
            pdfDoc.Close();

            // Secure PDF file
            PdfReader        pdfReader        = new PdfReader(newNonSecureFile);
            WriterProperties writerProperties = new WriterProperties();

            writerProperties.SetStandardEncryption(USERPASS, OWNERPASS, EncryptionConstants.ALLOW_PRINTING, EncryptionConstants.ENCRYPTION_AES_128);
            PdfWriter   pdfWriter   = new PdfWriter(new FileStream(newSecureFile, FileMode.Create), writerProperties);
            PdfDocument pdfDocument = new PdfDocument(pdfReader, pdfWriter);

            pdfDocument.Close();

            // Messagebox to show completed
            MessageBox.Show("Secure PDF Completed!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);

            // Open PDF on completion
            if (chkOpen.Checked == true)
            {
                Process.Start(newSecureFile);
            }
            else
            {
                return;
            }

            // Delete non secure version of file
            File.Delete(newNonSecureFile);
        }