Repository navigation
Description
Running a few tests with the new version i encountered some shortcomings I'd like to point out.
The method i used for these tests is very simple:
private bool VerifyPdfCanBeImported(string filePath)
{
try
{
var document = PdfReader.Open(filePath, PdfDocumentOpenMode.Import);
var documentCopy = new PdfDocument();
foreach (var page in document.Pages)
{
documentCopy.AddPage(page);
}
documentCopy.Save(Path.Combine(Path.GetTempPath(), "out.pdf"));
return true;
}
catch (Exception ex)
{
var message = string.Format("{0}:{1}{2}{1}{1}", filePath, Environment.NewLine, ex);
Console.WriteLine(message);
}
return false;
}
-
FlateDecode skips PNG-Decoding
Exception:
PdfSharp.Pdf.IO.PdfReaderException: Unexpected token '' in PDF stream. The file may be corrupted. If you think this is a bug in PDFsharp, please send us your PDF file.
(the token can be anything, it is not limited to an empty string)
It seems there are only a few lines of code missing in methodFlateDecode.Decode.
BetweenmsOutput.Flush()andreturn msOutput.GetBuffer()these lines are missing:if (msOutput.Length >= 0) { msOutput.Capacity = (int)msOutput.Length; if (parms?.DecodeParms != null) return StreamDecoder.Decode(msOutput.GetBuffer(), parms.DecodeParms); }These lines are present at the end of the file (in the
#elseblock), as well as inLzwDecode.Decode
-
Improper handling of encrypted object-streams
Exception:
System.IO.InvalidDataException: The archive entry was compressed using an unsupported compression method.
This happens with encrypted documents containing object-streams (which are encrypted).
When the parser encounters an object stream in the PDF, it immediately tries to extract the objects from the stream.
Problem is, the object stream is still encrypted (decryption happens after all objects are read).
When the object stream is flate-encoded, the decoder tries to deflate encrpyted data, leading to the mentioned exception.
I was able to fix this by inserting the following lines at the beginning ofPdfObjectStream.PdfObjectStream(PdfDictionary dict):// while objects inside an object-stream are not encrypted, the object-streams themself ARE ! // 7.5.7, Page 47: // In an encrypted file (i.e., entire object stream is encrypted), // strings occurring anywhere in an object stream shall not be separately encrypted. var xrefEncrypt = _document._trailer.Elements[PdfTrailer.Keys.Encrypt] as PdfReference; if (xrefEncrypt != null && _document.SecurityHandler != null) _document.SecurityHandler.DecryptObject(dict);The method
PdfStandardSecurityHandler.DecryptObjecthad to be madeinternalfor this to work.
You also have to make sure, you're not decrypting the streams again when the whole document is decrypted.
I simply used a flag inPdfStandardSecurityHandlerand inserted the following code at the beginning ofPdfStandardSecurityHandler.DecryptDictionary:// skip objects read from object streams (already done in PdfObjectStream.ctor()) if (skipObjectStreams && (dict.Elements.GetName("/Type") == "/ObjStm" || dict.Reference != null && dict.Reference.Position < 0)) return;The flag
skipObjectStreamsis set inPdfStandardSecurityHandler.DecryptDocument.
-
Improper calculation of decryption key (V5 R6)
Exception:
PdfSharp.Pdf.IO.PdfReaderException: The document seems to be not correctly encrypted. Could not verify P with Perms key.
In classPdfEncryptionV5the encryption key is not calculated correctly.
In MethodGetUserOwnerKeySaltthere is this single line of code:return userOwnerValue.Skip(40).ToArray();The issue could be fixed by replacing it with this line:
return userOwnerValue.Skip(40).Take(8).ToArray(); -
Also encryption-related but merely a suggestion/question.
Some documents i encountered (which are AES-encrypted) seem to be incompletely/incorrectly encrypted.
When importing these documents, aCryptographicExceptionis throw with the error messagePadding is invalid and cannot be removed.
Looking at the supposedly encrypted data as a hex-dump i realized, the data was in fact NOT encrypted (i.e. it contained readable text).
I would therefore suggest surrounding the code in methodDecryptForEnteredObject(ref byte[] bytes)(in classesPdfEncryptionV5andPdfEncryptionV1To4) with a try -> catch -> ignore block.
That would make documents exhibiting this issue readable.
If there is something inherently wrong with the encryption of a document, the library will probably bail out somewhere else, but I'm not 100% sure about that as I've never encountered a document like that.
Attached is a zip containing a document for each point in this list for reproduction.
documents.zip
If it helps, i could create separate issues for each point as well as pull-requests.
Activity
StLange commentedon Apr 11, 2023
Thank you for your excellent feedback, pull-requests are not necessary. We will come back to it very soon. This week we are still on Easter vacation.
StLange commentedon Apr 27, 2023
The bugs are fixed in Preview-2 that we published yesterday. We also ignore encryption errors caused by buggy PDF files as the default behavior.