none
C# proteger arquivo PDF com senha RRS feed

  • Pergunta

  • Bom dia, prezados!

    Preciso criar um método que protege um arquivo pdf com senha, alguém tem algum exemplo em C#?

    Este arquivo tenho ele tanto na base64 como no diretório

    Desde já agradeço pela ajuda

    segunda-feira, 5 de abril de 2021 15:33

Respostas

  • Carlos,

       Interessante... nunca fiz isto.
       Pesquisei alguns links que talvez te ajude:

    ======================================
    PDF protegido por senha usando C #

    https://csharp.docow.com/1731/pdf-protegido-por-senha-usando-c.html
    ======================================
    Gerar PDF protegido contra cópias Itextsharp

    https://social.msdn.microsoft.com/Forums/vstudio/pt-BR/9fe85a1d-211e-4b87-ba8b-373b7f0f58c7/gerar-pdf-protegido-contra-cpias-itextsharp?forum=aspnetpt
    ======================================
    Password protected PDF using C#

    using (Stream input = new FileStream("test.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
    using (Stream output = new FileStream("test_encrypted.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
    {
        PdfReader reader = new PdfReader(input);
        PdfEncryptor.Encrypt(reader, output, true, "secret", "secret", PdfWriter.ALLOW_PRINTING);
    }


    https://stackoverflow.com/questions/370571/password-protected-pdf-using-c-sharp
    ======================================
    How to: Protect a PDF Document with a Password

    using DevExpress.Pdf;
    
    namespace PDFPasswordProtection {
        class Program {
            static void Main(string[] args) {
    
                using (PdfDocumentProcessor pdfDocumentProcessor = new PdfDocumentProcessor()) {
    
                    // Load a PDF document.
                    pdfDocumentProcessor.LoadDocument("..\\..\\Demo.pdf");
    
                    // Specify printing, data extraction, modification, and interactivity permissions. 
                    PdfEncryptionOptions encryptionOptions = new PdfEncryptionOptions();
                    encryptionOptions.PrintingPermissions = PdfDocumentPrintingPermissions.Allowed;
                    encryptionOptions.DataExtractionPermissions = PdfDocumentDataExtractionPermissions.NotAllowed;
                    encryptionOptions.ModificationPermissions = PdfDocumentModificationPermissions.DocumentAssembling;
                    encryptionOptions.InteractivityPermissions = PdfDocumentInteractivityPermissions.Allowed;
    
                    // Specify the owner and user passwords for the document.  
                    encryptionOptions.OwnerPasswordString = "OwnerPassword";
                    encryptionOptions.UserPasswordString = "UserPassword";
    
                    // Specify the 256-bit AES encryption algorithm.
                    encryptionOptions.Algorithm = PdfEncryptionAlgorithm.AES256;
    
                    // Save the protected document with encryption settings.  
                    pdfDocumentProcessor.SaveDocument("..\\..\\ProtectedDocument.pdf", new PdfSaveOptions() { EncryptionOptions = encryptionOptions });
                }
            }
        }
    }


    https://docs.devexpress.com/OfficeFileAPI/114054/pdf-document-api/examples/document-protection/how-to-protect-a-pdf-document-with-a-password
    ======================================

    []'s,
    Fabio I.

    • Editado Fabio I segunda-feira, 5 de abril de 2021 16:45
    • Marcado como Resposta Carlos_rodrigues segunda-feira, 5 de abril de 2021 20:51
    segunda-feira, 5 de abril de 2021 16:44

Todas as Respostas

  • Carlos,

       Interessante... nunca fiz isto.
       Pesquisei alguns links que talvez te ajude:

    ======================================
    PDF protegido por senha usando C #

    https://csharp.docow.com/1731/pdf-protegido-por-senha-usando-c.html
    ======================================
    Gerar PDF protegido contra cópias Itextsharp

    https://social.msdn.microsoft.com/Forums/vstudio/pt-BR/9fe85a1d-211e-4b87-ba8b-373b7f0f58c7/gerar-pdf-protegido-contra-cpias-itextsharp?forum=aspnetpt
    ======================================
    Password protected PDF using C#

    using (Stream input = new FileStream("test.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
    using (Stream output = new FileStream("test_encrypted.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
    {
        PdfReader reader = new PdfReader(input);
        PdfEncryptor.Encrypt(reader, output, true, "secret", "secret", PdfWriter.ALLOW_PRINTING);
    }


    https://stackoverflow.com/questions/370571/password-protected-pdf-using-c-sharp
    ======================================
    How to: Protect a PDF Document with a Password

    using DevExpress.Pdf;
    
    namespace PDFPasswordProtection {
        class Program {
            static void Main(string[] args) {
    
                using (PdfDocumentProcessor pdfDocumentProcessor = new PdfDocumentProcessor()) {
    
                    // Load a PDF document.
                    pdfDocumentProcessor.LoadDocument("..\\..\\Demo.pdf");
    
                    // Specify printing, data extraction, modification, and interactivity permissions. 
                    PdfEncryptionOptions encryptionOptions = new PdfEncryptionOptions();
                    encryptionOptions.PrintingPermissions = PdfDocumentPrintingPermissions.Allowed;
                    encryptionOptions.DataExtractionPermissions = PdfDocumentDataExtractionPermissions.NotAllowed;
                    encryptionOptions.ModificationPermissions = PdfDocumentModificationPermissions.DocumentAssembling;
                    encryptionOptions.InteractivityPermissions = PdfDocumentInteractivityPermissions.Allowed;
    
                    // Specify the owner and user passwords for the document.  
                    encryptionOptions.OwnerPasswordString = "OwnerPassword";
                    encryptionOptions.UserPasswordString = "UserPassword";
    
                    // Specify the 256-bit AES encryption algorithm.
                    encryptionOptions.Algorithm = PdfEncryptionAlgorithm.AES256;
    
                    // Save the protected document with encryption settings.  
                    pdfDocumentProcessor.SaveDocument("..\\..\\ProtectedDocument.pdf", new PdfSaveOptions() { EncryptionOptions = encryptionOptions });
                }
            }
        }
    }


    https://docs.devexpress.com/OfficeFileAPI/114054/pdf-document-api/examples/document-protection/how-to-protect-a-pdf-document-with-a-password
    ======================================

    []'s,
    Fabio I.

    • Editado Fabio I segunda-feira, 5 de abril de 2021 16:45
    • Marcado como Resposta Carlos_rodrigues segunda-feira, 5 de abril de 2021 20:51
    segunda-feira, 5 de abril de 2021 16:44
  • Obrigado Fabio, ajudou muito!

    Consegui fazer com os links que vc enviou,  vou colocar aqui como ficou a versão final.

    segunda-feira, 5 de abril de 2021 20:53
  • using System;
    using System.IO;
    using iText.Kernel.Pdf;
    
    namespace ProtegerArquivoItext7
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("************************************************");
                Encrypt(@"C:\minvpw_T.pdf");
            }
    
            static void Encrypt(string file)
            {
                byte[] ownerPasss = System.Text.Encoding.ASCII.GetBytes("123");
                byte[] userPass = System.Text.Encoding.ASCII.GetBytes("123");
    
           
    
                using (Stream input=new FileStream(file, FileMode.Open ,FileAccess.Read, FileShare.Read))
                using (Stream output=new FileStream(@"C:\minvpw_T2.pdf",FileMode.Create,FileAccess.Write,FileShare.None) )
                {
                    PdfReader pdfReader = new PdfReader(input);
                    WriterProperties props = new WriterProperties().SetStandardEncryption(userPass, ownerPasss,
                    EncryptionConstants.ALLOW_PRINTING,
                    EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA
                    );
    
                    PdfWriter writer = new PdfWriter(output, props);
                    PdfDocument pdfDoc = new PdfDocument(pdfReader, writer);
                    pdfDoc.Close();
                }
            }
        }
    }
    

    • Sugerido como Resposta Fabio I segunda-feira, 5 de abril de 2021 22:50
    segunda-feira, 5 de abril de 2021 20:55
  • Carlos,

       Que bom que conseguiu. Obrigado por m pontuar. Vou analisar este código mais detalhes depois.

    Obrigado,

    Fabio I.

    • Editado Fabio I segunda-feira, 5 de abril de 2021 22:52
    segunda-feira, 5 de abril de 2021 22:51