empira / PDFsharp-1.5

A .NET library for processing PDF
MIT License
1.28k stars 588 forks source link

Unable to open a owner-protected document when the document ID starts with FEFF #118

Closed scasteran closed 1 year ago

scasteran commented 4 years ago

Expected Behavior

Being able to open a owner-password protected file: HelloWorld.pdf

Actual Behavior

Exception: A password is required to open the PDF document.

Steps to Reproduce the Behavior

PDFsharp-IssueSubmission.zip

wmsoto commented 4 years ago

Even though the chances of this happening are pretty low, this seems like a legit fix. Hope it gets merged in soon!

jbherbert commented 3 years ago

I had this problem. In the wait of the merged fix, one could use the following function to "correct" the problem by avoiding the offending value like that :

        /// <summary>
        /// This function is to overcome a problem with PdfSharp when the ID in the trailer of the PDF begins with 0xFEFF.
        /// If we have this case (begins with FEFF), just change the ID to a random guid.
        /// This bug should be fixed in next PdfSharp version (somewhere > 1.51.5185).
        /// <see cref="https://github.com/empira/PDFsharp/issues/118"/>
        /// </summary>
        /// <param name="pdfDocument"></param>
        public static void PdfDocumentIdCorrection(PdfSharp.Pdf.PdfDocument pdfDocument)
        {
            if (pdfDocument.Internals.FirstDocumentID.Length != 16)
            {
                var bytes = Guid.NewGuid().ToByteArray().SelectMany(b => new byte[] { b, 0 }).ToArray();
                bytes[0] = (bytes[0] == 0xfe) ? (byte)0xfa : bytes[0]; // ensure it won't begin by 0xFEFF.
                pdfDocument.Internals.FirstDocumentID = System.Text.Encoding.Unicode.GetString(bytes);
            }
        }
ThomasHoevel commented 1 year ago

Fix included in PDFsharp 6.0.0. Thanks for the feedback.