Repository navigation
feat(kernel): add the decrypt side of the Standard security handler - #207
Merged
Merged
Conversation
Covers every /V+/R combination the committed corpus (#99) exercises, V=1/R=2 through V=5/R=6, entirely internal: no public surface, no PdfReader wiring, no /Encrypt gate. Promotes Hash2B, PasswordBytes and Concat on StandardSecurityHandler from private to internal so the new decryptor reuses them instead of duplicating the write-side logic. Verified against all eight fixtures: both passwords derive the file key and a wrong one fails cleanly, and a decrypted content stream matches qpdf's own plaintext byte-for-byte, not merely something self-consistent. An empty user password, absent from the corpus, is covered by independently computed vectors instead.
Constructor_atRevision5_requiresOeAndUe passed o: new byte[32] at r: 6, which trips the /O length guard before the /OE check runs, so the exception it caught never came from the code under test. Deleting both the /OE and /UE presence checks left all tests green. Split into two tests, each with /O and /U already the right length so only the guard under test can throw.
Checked against the PDF Association's errata index for ISO 32000-2: /CFM belongs to §7.6.6 (Crypt filters), not §7.6.4.2 Table 25. The R>=5 /O and /U layout cites §7.6.4.3.5/.3.6, subclauses that don't exist — 7.6.4.3 ends at .4; the real cite is Algorithms 8 and 9 under §7.6.4.4. The AESV3 "file key used directly" case cited ISO 32000-1 §7.6.2 note c), but 32000-1:2008 predates V=5 entirely; that's ISO 32000-2 §7.6.3.3, Algorithm 1.A. And the R5 hash comment cited §7.6.4.3.3, which is Algorithm 2.A scoped to "revision 6 and later" — R5 predates the standard and has no clause of its own to cite.
§7.6.4.4.2 is Algorithm 3 (computing the /O entry, R<=4); what this method implements is Algorithm 10, §7.6.4.4.9. Predates this branch's decrypt-side work — the write side has carried the wrong cite since /Perms was first added.
Every R3/R4 vector in this file, corpus and synthetic alike, uses a 16-byte key, so a regression hardcoding the round loop's truncation length to 16 would pass all of them. /R 3 /Length 40 is a real producer combination this decryptor has to handle correctly. Independently computed in Python, not from the code under test, and exercises both the user path (Algorithm 2) and the owner path (Algorithm 7's key derivation feeding back into Algorithm 2).
Its own doc said a mismatch meant /P or /EncryptMetadata had been altered, but the method never received either value — it only checked the fixed "adb" marker, so /P edited to -4, -60, 0, or int.MinValue all still verified. qpdf catches this; this handler didn't. Now an instance method (both fields were already on the decryptor), comparing the decrypted block's first four bytes and byte 8 against /P and /EncryptMetadata, same as the existing byte-pinning test already asserted the plaintext should contain. Still advisory and non-gating, as before: ISO 32000-2 keeps key retrieval (Algorithm 2.A) and permission validation (Algorithm 13) as separate algorithms, neither says what a reader must do on mismatch, and qpdf itself warns without refusing to decrypt.
aes.Key = key sat outside the try in DecryptAesCbcWithIvPrefix, so a crafted /V 4 /Length 40 /CFM /AESV2 file (a 10-byte object key, not a legal AES size) threw a bare CryptographicException instead of the InvalidDataException every other malformed-file path here raises. Widened the try to cover key assignment and decryptor creation too.
The guard's own message already said "(1, 2, 4 or 5)" but the check let 3 through anyway. /V 3 is Adobe's undocumented algorithm; treating it as V=2 RC4 would decrypt to garbage instead of failing cleanly.
PasswordBytes is UTF-8, correct for R>=5's Algorithm 8/9. Whether R<=4's Algorithm 2 wants the same encoding or the Latin-1/ PDFDocEncoding convention that predates PDF 2.0 is unconfirmed here — attempts to check it against the ISO 32000-1 text directly didn't succeed, and secondary sources disagree enough to not act on it. Behaviour unchanged; the open question is now written down instead of silent.
R>=5's Algorithm 2.A never reads /ID[0] — only R<=4's Algorithm 2 and 5 do — so a V5/R6 file with an empty /ID was being rejected for a reason that doesn't apply to it. Moved the check into the R<=4 branch.
The old comment claimed hex bytes kept "sAlT" from reading as English prose to the clean-room check, but that check matches two fixed library-name tokens, not prose, and the literal string "sAlT" already appears three times in this file's comments regardless. Hex form is kept — it reads more clearly next to PaddingString above — with a reason that's actually true.
Both directions run the same 20 RC4 passes, not "one more" than Algorithm 5's forward direction. Also note why: RC4 XORs data against a keystream that depends only on the key and the fixed 32-byte data length, so composing 20 such keystreams by XOR is order-independent — reversing the loop is an equivalent mutant, which is why nothing here pins the iteration direction.
/Perms only exists at R>=5, and only an R>=5 file key is AES-256 sized. aes.Key's setter sat outside any try, so an R2 file with a 5-byte key raised a raw CryptographicException instead of a clean false, and an R4 file with a 16-byte key (a legal AES-128 size) silently ran ECB decryption on bytes that were never a /Perms block and returned a meaningless boolean.
Three citations were wrong and one comment mixed up which reader wrote them: - the CBC IV rule pointed at "§7.6.2 note c", which does not exist; it's Algorithm 1 step (d). - /U's trailing 16 bytes (R>=3) were described as "Algorithm 5's own output"; Algorithm 5's RC4 chain only ever produces 16 bytes, and step (f) calls the rest arbitrary padding. - /O's 20 RC4 passes were attributed to Algorithm 5, which builds /U and never touches /O; they're Algorithm 3 steps (f)+(g). - the crypt-filter-method doc cited §7.6.5, which is Crypt Filters and requires V=4 — the opposite of the V=1/V=2 implicit case it was meant to describe. That's Algorithm 1 in §7.6.2. Also records why the fifty-round MD5 truncation in the owner-password path is correct despite the ISO text: Algorithm 7 delegates to Algorithm 3 step (c), which describes no truncation, unlike Algorithm 2 step (h)'s "first n bytes" wording that the user-password path implements. Built both readings as real R3 /Length 40 files: qpdf 12.3.2 and poppler 25.07 both reject the literal (non-truncating) one and accept the truncating one, so interoperability settles it in favor of what this code already does. Cites the Adobe Supplement to the ISO 32000 (BaseVersion 1.7, ExtensionLevel 3, §3.5.2) for the R5 hash, which has no ISO 32000-2 clause of its own, and for the R<=4 password character encoding question (PDFDocEncoding, not Latin-1), which ISO 32000-1 §7.6 never addresses at all.
Identity returns ciphertext as plaintext with no error, and it's the mapping a wiring author would naturally reach for on a /StmF or /StrF naming a /CF entry that doesn't exist — silently corrupting an entire document. Add CryptFilterMethod.Unsupported, whose Decrypt case throws InvalidDataException, and convert the two ArgumentOutOfRange exceptions in ComputeObjectKey (negative object number, negative generation) to InvalidDataException: both values come from the file itself, not caller code, so a negative one is a malformed-file condition rather than a programming error.
- DecryptAesCbcWithIvPrefix's comment claimed the object key could be "too short or too long"; ComputeObjectKey never returns more than 16 bytes, so "too long" isn't reachable. - Constructor_rejectsV3's comment said V=3 would "silently treat the file as V=2 RC4" — this class never derives an algorithm from _v; the filter methods are constructor parameters. - Constructor_atRevision5_requiresOe/_requiresUe both constructed r: 6; changed to r: 5 so the name matches what's under test (the guard is R>=5 generally, and R6 is already covered elsewhere). - Varied two of four repeated "not merely X" / "not just Y" phrasings in the class summary and the CHANGELOG entry.
Every fixture in the corpus has /StmF and /StrF naming the same /CFM, and every existing test passes the same fileKey/data through both methods, so nothing distinguished DecryptStream from DecryptString: swapping the two constructor assignments survived, and gutting DecryptString to return its input unchanged survived too. Add two tests with deliberately mismatched stream/string filters (Identity/RC4 both ways) plus a direct Identity round trip, since `case Identity: return data.ToArray()` could regress to returning an empty array with the suite still green.
data.Length < 16 || (data.Length - 16) % 16 != 0 had no test at all; dropping it wholesale still passed the suite. Add 15- and 31-byte inputs (too short for the IV, and IV-plus-a-partial-block). Also add a wrong-but-legal-size (32-byte) key: the only existing test aimed at the padding-failure catch block actually trips aes.Key's setter on a too-short key, never TransformFinalBlock's own rejection of bad PKCS#7 padding, so moving TransformFinalBlock outside the try block would have passed unnoticed.
VerifyPermissions_detectsATamperedPValue tampered with info.P ^ -1, flipping all 32 bits, so narrowing the four-byte comparison against /Perms down to a single byte would still pass. Flip one permission bit instead, so the test only passes if all four bytes are compared.
Deleting the marker check survived every existing test: the wrong-key tests already fail on an unrelated comparison (garbage plaintext, so /P mismatches too), and the tamper tests only ever corrupt /P or /EncryptMetadata. Build a /Perms block by hand with a correct /P and /EncryptMetadata but a corrupted marker, so the marker check is the only thing that can make it fail.
`v is < 1 or > 5 or 3` narrowed to `v is 3`, and the /R range check deleted outright, both left every existing test green. Add V=0, V=6, R=1 and R=7 cases. Also fill in five field-length guards that had no test of their own: /U at R<5 (only /O was pinned), keyLengthBytes outside 5-16 at R<5, /O and /U at 48 bytes for R>=5, and keyLengthBytes != 32 for R>=5. The R>=5 /U guard is the sharpest of the five: without it, TryComputeFileKeyFromUserPassword's `_u.AsSpan(32, 8)` on a 32-byte /U throws ArgumentOutOfRangeException from inside the password path instead of failing cleanly up front.
min(fileKey.Length + 5, 16) and min(fileKey.Length * 2, 16) agree at every key length this file's other vectors use (5 and 16), so a regression to the second formula would still pass. 7 bytes is the smallest length where they diverge (12 vs. 14), computed independently with Python's hashlib, not by running the code under test.
The first test where StandardSecurityHandler.ComputePerms (write) and StandardSecurityDecryptor.VerifyPermissions (read) meet on /Perms with /EncryptMetadata false. Every other R6 /Perms test, in this file and in EncryptionTests, only ever runs with the default true, so ComputePerms hardcoding block[8] = 'T' instead of branching on the setting would survive both suites.
The new /EncryptMetadata-false test and a CHANGELOG rewording both introduced another instance of the same contrastive phrasing the earlier nits commit was trying to cut down on.
Tim81
added a commit
that referenced
this pull request
Aug 28, 2026
Third and last PR for #97, after the RC4/MD5 primitives (#203) and the decrypt algorithms (#207). Wires them into the reader and ships the public surface. PdfReader.Open(bytes, password) opens Standard-security-handler documents at /V 1, 2, 4 and 5 and /R 2 through 6 — RC4-40 through RC4-128, AES-128 and AES-256 — plus the /Crypt filter and crypt filters naming different methods for strings and streams. Strings are decrypted in Resolve under the identity of the indirect object containing them (ISO 32000-1 §7.6.2, Algorithm 1) and stream bodies on the decode path; ParsedStream.RawBody still holds the verbatim file bytes, which StreamRule and HexStringRule need for byte offsets. Two behavioural breaks, both under Breaking changes in the CHANGELOG. A password-protected document now reaches PdfPreflight as PdfPasswordException, which does not derive from NotSupportedException, so a caller that caught the old UnsupportedPdfFeatureException to detect an encrypted file no longer catches it. And PdfDocument.DocumentId refuses a value that is not 16 bytes, where any other length was previously written as no /ID at all, silently — which produced an encrypted document qpdf rejects outright. A signature dictionary's /Contents is never decrypted. ISO 32000-1 says nothing either way; a signer patches those hex digits into already-serialized bytes, so decrypting them corrupts /ByteRange verification. Measured against qpdf across five signature shapes, and stated in full in the CHANGELOG. Reviewed over ten adversarial rounds. The ninth and earlier each found real defects, among them a cache-poisoning bug that left an object cached as ciphertext, a file key not required to be random, and /U's two salts not required to differ. The tenth found none: three independent reviewers ran 107 mutations, one built a reference implementation of §7.6 from the spec and a 312-file differential corpus, and all 312 open and decrypt correctly. What that round found was five places where the suite was green for the wrong reason, all now joined and each verified to kill its own mutation. Closes #97.
Tim81
added a commit
that referenced
this pull request
Sep 6, 2026
…207) * feat(kernel): add decrypt side of the Standard security handler Covers every /V+/R combination the committed corpus (#99) exercises, V=1/R=2 through V=5/R=6, entirely internal: no public surface, no PdfReader wiring, no /Encrypt gate. Promotes Hash2B, PasswordBytes and Concat on StandardSecurityHandler from private to internal so the new decryptor reuses them instead of duplicating the write-side logic. Verified against all eight fixtures: both passwords derive the file key and a wrong one fails cleanly, and a decrypted content stream matches qpdf's own plaintext byte-for-byte, not merely something self-consistent. An empty user password, absent from the corpus, is covered by independently computed vectors instead. * fix(kernel): pin the R>=5 /OE and /UE guards independently Constructor_atRevision5_requiresOeAndUe passed o: new byte[32] at r: 6, which trips the /O length guard before the /OE check runs, so the exception it caught never came from the code under test. Deleting both the /OE and /UE presence checks left all tests green. Split into two tests, each with /O and /U already the right length so only the guard under test can throw. * docs(kernel): fix wrong ISO 32000-2 clause numbers in the decryptor Checked against the PDF Association's errata index for ISO 32000-2: /CFM belongs to §7.6.6 (Crypt filters), not §7.6.4.2 Table 25. The R>=5 /O and /U layout cites §7.6.4.3.5/.3.6, subclauses that don't exist — 7.6.4.3 ends at .4; the real cite is Algorithms 8 and 9 under §7.6.4.4. The AESV3 "file key used directly" case cited ISO 32000-1 §7.6.2 note c), but 32000-1:2008 predates V=5 entirely; that's ISO 32000-2 §7.6.3.3, Algorithm 1.A. And the R5 hash comment cited §7.6.4.3.3, which is Algorithm 2.A scoped to "revision 6 and later" — R5 predates the standard and has no clause of its own to cite. * fix(kernel): correct ComputePerms's stale ISO clause number §7.6.4.4.2 is Algorithm 3 (computing the /O entry, R<=4); what this method implements is Algorithm 10, §7.6.4.4.9. Predates this branch's decrypt-side work — the write side has carried the wrong cite since /Perms was first added. * test(kernel): pin the fifty-round key length at R3 with a 5-byte key Every R3/R4 vector in this file, corpus and synthetic alike, uses a 16-byte key, so a regression hardcoding the round loop's truncation length to 16 would pass all of them. /R 3 /Length 40 is a real producer combination this decryptor has to handle correctly. Independently computed in Python, not from the code under test, and exercises both the user path (Algorithm 2) and the owner path (Algorithm 7's key derivation feeding back into Algorithm 2). * fix(kernel): make VerifyPermissions check /P and /EncryptMetadata Its own doc said a mismatch meant /P or /EncryptMetadata had been altered, but the method never received either value — it only checked the fixed "adb" marker, so /P edited to -4, -60, 0, or int.MinValue all still verified. qpdf catches this; this handler didn't. Now an instance method (both fields were already on the decryptor), comparing the decrypted block's first four bytes and byte 8 against /P and /EncryptMetadata, same as the existing byte-pinning test already asserted the plaintext should contain. Still advisory and non-gating, as before: ISO 32000-2 keeps key retrieval (Algorithm 2.A) and permission validation (Algorithm 13) as separate algorithms, neither says what a reader must do on mismatch, and qpdf itself warns without refusing to decrypt. * fix(kernel): stop CryptographicException escaping a bad AES key aes.Key = key sat outside the try in DecryptAesCbcWithIvPrefix, so a crafted /V 4 /Length 40 /CFM /AESV2 file (a 10-byte object key, not a legal AES size) threw a bare CryptographicException instead of the InvalidDataException every other malformed-file path here raises. Widened the try to cover key assignment and decryptor creation too. * fix(kernel): reject /Encrypt /V 3 The guard's own message already said "(1, 2, 4 or 5)" but the check let 3 through anyway. /V 3 is Adobe's undocumented algorithm; treating it as V=2 RC4 would decrypt to garbage instead of failing cleanly. * docs(kernel): record the open question on R<=4 password encoding PasswordBytes is UTF-8, correct for R>=5's Algorithm 8/9. Whether R<=4's Algorithm 2 wants the same encoding or the Latin-1/ PDFDocEncoding convention that predates PDF 2.0 is unconfirmed here — attempts to check it against the ISO 32000-1 text directly didn't succeed, and secondary sources disagree enough to not act on it. Behaviour unchanged; the open question is now written down instead of silent. * fix(kernel): scope the /ID[0]-required guard to R<=4 R>=5's Algorithm 2.A never reads /ID[0] — only R<=4's Algorithm 2 and 5 do — so a V5/R6 file with an empty /ID was being rejected for a reason that doesn't apply to it. Moved the check into the R<=4 branch. * docs(kernel): fix the AesSalt hex-encoding rationale The old comment claimed hex bytes kept "sAlT" from reading as English prose to the clean-room check, but that check matches two fixed library-name tokens, not prose, and the literal string "sAlT" already appears three times in this file's comments regardless. Hex form is kept — it reads more clearly next to PaddingString above — with a reason that's actually true. * docs(kernel): fix the Algorithm 7 reverse-pass comment Both directions run the same 20 RC4 passes, not "one more" than Algorithm 5's forward direction. Also note why: RC4 XORs data against a keystream that depends only on the key and the fixed 32-byte data length, so composing 20 such keystreams by XOR is order-independent — reversing the loop is an equivalent mutant, which is why nothing here pins the iteration direction. * fix(kernel): stop VerifyPermissions throwing below R5 /Perms only exists at R>=5, and only an R>=5 file key is AES-256 sized. aes.Key's setter sat outside any try, so an R2 file with a 5-byte key raised a raw CryptographicException instead of a clean false, and an R4 file with a 16-byte key (a legal AES-128 size) silently ran ECB decryption on bytes that were never a /Perms block and returned a meaningless boolean. * docs(kernel): fix wrong ISO citations and the truncation rationale Three citations were wrong and one comment mixed up which reader wrote them: - the CBC IV rule pointed at "§7.6.2 note c", which does not exist; it's Algorithm 1 step (d). - /U's trailing 16 bytes (R>=3) were described as "Algorithm 5's own output"; Algorithm 5's RC4 chain only ever produces 16 bytes, and step (f) calls the rest arbitrary padding. - /O's 20 RC4 passes were attributed to Algorithm 5, which builds /U and never touches /O; they're Algorithm 3 steps (f)+(g). - the crypt-filter-method doc cited §7.6.5, which is Crypt Filters and requires V=4 — the opposite of the V=1/V=2 implicit case it was meant to describe. That's Algorithm 1 in §7.6.2. Also records why the fifty-round MD5 truncation in the owner-password path is correct despite the ISO text: Algorithm 7 delegates to Algorithm 3 step (c), which describes no truncation, unlike Algorithm 2 step (h)'s "first n bytes" wording that the user-password path implements. Built both readings as real R3 /Length 40 files: qpdf 12.3.2 and poppler 25.07 both reject the literal (non-truncating) one and accept the truncating one, so interoperability settles it in favor of what this code already does. Cites the Adobe Supplement to the ISO 32000 (BaseVersion 1.7, ExtensionLevel 3, §3.5.2) for the R5 hash, which has no ISO 32000-2 clause of its own, and for the R<=4 password character encoding question (PDFDocEncoding, not Latin-1), which ISO 32000-1 §7.6 never addresses at all. * fix(kernel): fail loudly on an unrecognised crypt filter Identity returns ciphertext as plaintext with no error, and it's the mapping a wiring author would naturally reach for on a /StmF or /StrF naming a /CF entry that doesn't exist — silently corrupting an entire document. Add CryptFilterMethod.Unsupported, whose Decrypt case throws InvalidDataException, and convert the two ArgumentOutOfRange exceptions in ComputeObjectKey (negative object number, negative generation) to InvalidDataException: both values come from the file itself, not caller code, so a negative one is a malformed-file condition rather than a programming error. * docs(kernel): tidy four review nits in the decryptor and its tests - DecryptAesCbcWithIvPrefix's comment claimed the object key could be "too short or too long"; ComputeObjectKey never returns more than 16 bytes, so "too long" isn't reachable. - Constructor_rejectsV3's comment said V=3 would "silently treat the file as V=2 RC4" — this class never derives an algorithm from _v; the filter methods are constructor parameters. - Constructor_atRevision5_requiresOe/_requiresUe both constructed r: 6; changed to r: 5 so the name matches what's under test (the guard is R>=5 generally, and R6 is already covered elsewhere). - Varied two of four repeated "not merely X" / "not just Y" phrasings in the class summary and the CHANGELOG entry. * test(kernel): pin DecryptStream vs DecryptString dispatch Every fixture in the corpus has /StmF and /StrF naming the same /CFM, and every existing test passes the same fileKey/data through both methods, so nothing distinguished DecryptStream from DecryptString: swapping the two constructor assignments survived, and gutting DecryptString to return its input unchanged survived too. Add two tests with deliberately mismatched stream/string filters (Identity/RC4 both ways) plus a direct Identity round trip, since `case Identity: return data.ToArray()` could regress to returning an empty array with the suite still green. * test(kernel): pin the AES-CBC length guard and padding failure data.Length < 16 || (data.Length - 16) % 16 != 0 had no test at all; dropping it wholesale still passed the suite. Add 15- and 31-byte inputs (too short for the IV, and IV-plus-a-partial-block). Also add a wrong-but-legal-size (32-byte) key: the only existing test aimed at the padding-failure catch block actually trips aes.Key's setter on a too-short key, never TransformFinalBlock's own rejection of bad PKCS#7 padding, so moving TransformFinalBlock outside the try block would have passed unnoticed. * test(kernel): sharpen the /P tamper test to a single bit VerifyPermissions_detectsATamperedPValue tampered with info.P ^ -1, flipping all 32 bits, so narrowing the four-byte comparison against /Perms down to a single byte would still pass. Flip one permission bit instead, so the test only passes if all four bytes are compared. * test(kernel): pin the "adb" marker check inside VerifyPermissions Deleting the marker check survived every existing test: the wrong-key tests already fail on an unrelated comparison (garbage plaintext, so /P mismatches too), and the tamper tests only ever corrupt /P or /EncryptMetadata. Build a /Perms block by hand with a correct /P and /EncryptMetadata but a corrupted marker, so the marker check is the only thing that can make it fail. * test(kernel): pin /V, /R and the constructor's length guards `v is < 1 or > 5 or 3` narrowed to `v is 3`, and the /R range check deleted outright, both left every existing test green. Add V=0, V=6, R=1 and R=7 cases. Also fill in five field-length guards that had no test of their own: /U at R<5 (only /O was pinned), keyLengthBytes outside 5-16 at R<5, /O and /U at 48 bytes for R>=5, and keyLengthBytes != 32 for R>=5. The R>=5 /U guard is the sharpest of the five: without it, TryComputeFileKeyFromUserPassword's `_u.AsSpan(32, 8)` on a 32-byte /U throws ArgumentOutOfRangeException from inside the password path instead of failing cleanly up front. * test(kernel): pin the object-key truncation at a non-corpus length min(fileKey.Length + 5, 16) and min(fileKey.Length * 2, 16) agree at every key length this file's other vectors use (5 and 16), so a regression to the second formula would still pass. 7 bytes is the smallest length where they diverge (12 vs. 14), computed independently with Python's hashlib, not by running the code under test. * test(kernel): pin /EncryptMetadata false through write and read /Perms The first test where StandardSecurityHandler.ComputePerms (write) and StandardSecurityDecryptor.VerifyPermissions (read) meet on /Perms with /EncryptMetadata false. Every other R6 /Perms test, in this file and in EncryptionTests, only ever runs with the default true, so ComputePerms hardcoding block[8] = 'T' instead of branching on the setting would survive both suites. * docs(kernel): vary two more repeats of the "not merely/just" shape The new /EncryptMetadata-false test and a CHANGELOG rewording both introduced another instance of the same contrastive phrasing the earlier nits commit was trying to cut down on.
Tim81
added a commit
that referenced
this pull request
Sep 6, 2026
Third and last PR for #97, after the RC4/MD5 primitives (#203) and the decrypt algorithms (#207). Wires them into the reader and ships the public surface. PdfReader.Open(bytes, password) opens Standard-security-handler documents at /V 1, 2, 4 and 5 and /R 2 through 6 — RC4-40 through RC4-128, AES-128 and AES-256 — plus the /Crypt filter and crypt filters naming different methods for strings and streams. Strings are decrypted in Resolve under the identity of the indirect object containing them (ISO 32000-1 §7.6.2, Algorithm 1) and stream bodies on the decode path; ParsedStream.RawBody still holds the verbatim file bytes, which StreamRule and HexStringRule need for byte offsets. Two behavioural breaks, both under Breaking changes in the CHANGELOG. A password-protected document now reaches PdfPreflight as PdfPasswordException, which does not derive from NotSupportedException, so a caller that caught the old UnsupportedPdfFeatureException to detect an encrypted file no longer catches it. And PdfDocument.DocumentId refuses a value that is not 16 bytes, where any other length was previously written as no /ID at all, silently — which produced an encrypted document qpdf rejects outright. A signature dictionary's /Contents is never decrypted. ISO 32000-1 says nothing either way; a signer patches those hex digits into already-serialized bytes, so decrypting them corrupts /ByteRange verification. Measured against qpdf across five signature shapes, and stated in full in the CHANGELOG. Reviewed over ten adversarial rounds. The ninth and earlier each found real defects, among them a cache-poisoning bug that left an object cached as ciphertext, a file key not required to be random, and /U's two salts not required to differ. The tenth found none: three independent reviewers ran 107 mutations, one built a reference implementation of §7.6 from the spec and a 312-file differential corpus, and all 312 open and decrypt correctly. What that round found was five places where the suite was green for the wrong reason, all now joined and each verified to kill its own mutation. Closes #97.
Tim81
added a commit
that referenced
this pull request
Sep 6, 2026
…207) * feat(kernel): add decrypt side of the Standard security handler Covers every /V+/R combination the committed corpus (#99) exercises, V=1/R=2 through V=5/R=6, entirely internal: no public surface, no PdfReader wiring, no /Encrypt gate. Promotes Hash2B, PasswordBytes and Concat on StandardSecurityHandler from private to internal so the new decryptor reuses them instead of duplicating the write-side logic. Verified against all eight fixtures: both passwords derive the file key and a wrong one fails cleanly, and a decrypted content stream matches qpdf's own plaintext byte-for-byte, not merely something self-consistent. An empty user password, absent from the corpus, is covered by independently computed vectors instead. * fix(kernel): pin the R>=5 /OE and /UE guards independently Constructor_atRevision5_requiresOeAndUe passed o: new byte[32] at r: 6, which trips the /O length guard before the /OE check runs, so the exception it caught never came from the code under test. Deleting both the /OE and /UE presence checks left all tests green. Split into two tests, each with /O and /U already the right length so only the guard under test can throw. * docs(kernel): fix wrong ISO 32000-2 clause numbers in the decryptor Checked against the PDF Association's errata index for ISO 32000-2: /CFM belongs to §7.6.6 (Crypt filters), not §7.6.4.2 Table 25. The R>=5 /O and /U layout cites §7.6.4.3.5/.3.6, subclauses that don't exist — 7.6.4.3 ends at .4; the real cite is Algorithms 8 and 9 under §7.6.4.4. The AESV3 "file key used directly" case cited ISO 32000-1 §7.6.2 note c), but 32000-1:2008 predates V=5 entirely; that's ISO 32000-2 §7.6.3.3, Algorithm 1.A. And the R5 hash comment cited §7.6.4.3.3, which is Algorithm 2.A scoped to "revision 6 and later" — R5 predates the standard and has no clause of its own to cite. * fix(kernel): correct ComputePerms's stale ISO clause number §7.6.4.4.2 is Algorithm 3 (computing the /O entry, R<=4); what this method implements is Algorithm 10, §7.6.4.4.9. Predates this branch's decrypt-side work — the write side has carried the wrong cite since /Perms was first added. * test(kernel): pin the fifty-round key length at R3 with a 5-byte key Every R3/R4 vector in this file, corpus and synthetic alike, uses a 16-byte key, so a regression hardcoding the round loop's truncation length to 16 would pass all of them. /R 3 /Length 40 is a real producer combination this decryptor has to handle correctly. Independently computed in Python, not from the code under test, and exercises both the user path (Algorithm 2) and the owner path (Algorithm 7's key derivation feeding back into Algorithm 2). * fix(kernel): make VerifyPermissions check /P and /EncryptMetadata Its own doc said a mismatch meant /P or /EncryptMetadata had been altered, but the method never received either value — it only checked the fixed "adb" marker, so /P edited to -4, -60, 0, or int.MinValue all still verified. qpdf catches this; this handler didn't. Now an instance method (both fields were already on the decryptor), comparing the decrypted block's first four bytes and byte 8 against /P and /EncryptMetadata, same as the existing byte-pinning test already asserted the plaintext should contain. Still advisory and non-gating, as before: ISO 32000-2 keeps key retrieval (Algorithm 2.A) and permission validation (Algorithm 13) as separate algorithms, neither says what a reader must do on mismatch, and qpdf itself warns without refusing to decrypt. * fix(kernel): stop CryptographicException escaping a bad AES key aes.Key = key sat outside the try in DecryptAesCbcWithIvPrefix, so a crafted /V 4 /Length 40 /CFM /AESV2 file (a 10-byte object key, not a legal AES size) threw a bare CryptographicException instead of the InvalidDataException every other malformed-file path here raises. Widened the try to cover key assignment and decryptor creation too. * fix(kernel): reject /Encrypt /V 3 The guard's own message already said "(1, 2, 4 or 5)" but the check let 3 through anyway. /V 3 is Adobe's undocumented algorithm; treating it as V=2 RC4 would decrypt to garbage instead of failing cleanly. * docs(kernel): record the open question on R<=4 password encoding PasswordBytes is UTF-8, correct for R>=5's Algorithm 8/9. Whether R<=4's Algorithm 2 wants the same encoding or the Latin-1/ PDFDocEncoding convention that predates PDF 2.0 is unconfirmed here — attempts to check it against the ISO 32000-1 text directly didn't succeed, and secondary sources disagree enough to not act on it. Behaviour unchanged; the open question is now written down instead of silent. * fix(kernel): scope the /ID[0]-required guard to R<=4 R>=5's Algorithm 2.A never reads /ID[0] — only R<=4's Algorithm 2 and 5 do — so a V5/R6 file with an empty /ID was being rejected for a reason that doesn't apply to it. Moved the check into the R<=4 branch. * docs(kernel): fix the AesSalt hex-encoding rationale The old comment claimed hex bytes kept "sAlT" from reading as English prose to the clean-room check, but that check matches two fixed library-name tokens, not prose, and the literal string "sAlT" already appears three times in this file's comments regardless. Hex form is kept — it reads more clearly next to PaddingString above — with a reason that's actually true. * docs(kernel): fix the Algorithm 7 reverse-pass comment Both directions run the same 20 RC4 passes, not "one more" than Algorithm 5's forward direction. Also note why: RC4 XORs data against a keystream that depends only on the key and the fixed 32-byte data length, so composing 20 such keystreams by XOR is order-independent — reversing the loop is an equivalent mutant, which is why nothing here pins the iteration direction. * fix(kernel): stop VerifyPermissions throwing below R5 /Perms only exists at R>=5, and only an R>=5 file key is AES-256 sized. aes.Key's setter sat outside any try, so an R2 file with a 5-byte key raised a raw CryptographicException instead of a clean false, and an R4 file with a 16-byte key (a legal AES-128 size) silently ran ECB decryption on bytes that were never a /Perms block and returned a meaningless boolean. * docs(kernel): fix wrong ISO citations and the truncation rationale Three citations were wrong and one comment mixed up which reader wrote them: - the CBC IV rule pointed at "§7.6.2 note c", which does not exist; it's Algorithm 1 step (d). - /U's trailing 16 bytes (R>=3) were described as "Algorithm 5's own output"; Algorithm 5's RC4 chain only ever produces 16 bytes, and step (f) calls the rest arbitrary padding. - /O's 20 RC4 passes were attributed to Algorithm 5, which builds /U and never touches /O; they're Algorithm 3 steps (f)+(g). - the crypt-filter-method doc cited §7.6.5, which is Crypt Filters and requires V=4 — the opposite of the V=1/V=2 implicit case it was meant to describe. That's Algorithm 1 in §7.6.2. Also records why the fifty-round MD5 truncation in the owner-password path is correct despite the ISO text: Algorithm 7 delegates to Algorithm 3 step (c), which describes no truncation, unlike Algorithm 2 step (h)'s "first n bytes" wording that the user-password path implements. Built both readings as real R3 /Length 40 files: qpdf 12.3.2 and poppler 25.07 both reject the literal (non-truncating) one and accept the truncating one, so interoperability settles it in favor of what this code already does. Cites the Adobe Supplement to the ISO 32000 (BaseVersion 1.7, ExtensionLevel 3, §3.5.2) for the R5 hash, which has no ISO 32000-2 clause of its own, and for the R<=4 password character encoding question (PDFDocEncoding, not Latin-1), which ISO 32000-1 §7.6 never addresses at all. * fix(kernel): fail loudly on an unrecognised crypt filter Identity returns ciphertext as plaintext with no error, and it's the mapping a wiring author would naturally reach for on a /StmF or /StrF naming a /CF entry that doesn't exist — silently corrupting an entire document. Add CryptFilterMethod.Unsupported, whose Decrypt case throws InvalidDataException, and convert the two ArgumentOutOfRange exceptions in ComputeObjectKey (negative object number, negative generation) to InvalidDataException: both values come from the file itself, not caller code, so a negative one is a malformed-file condition rather than a programming error. * docs(kernel): tidy four review nits in the decryptor and its tests - DecryptAesCbcWithIvPrefix's comment claimed the object key could be "too short or too long"; ComputeObjectKey never returns more than 16 bytes, so "too long" isn't reachable. - Constructor_rejectsV3's comment said V=3 would "silently treat the file as V=2 RC4" — this class never derives an algorithm from _v; the filter methods are constructor parameters. - Constructor_atRevision5_requiresOe/_requiresUe both constructed r: 6; changed to r: 5 so the name matches what's under test (the guard is R>=5 generally, and R6 is already covered elsewhere). - Varied two of four repeated "not merely X" / "not just Y" phrasings in the class summary and the CHANGELOG entry. * test(kernel): pin DecryptStream vs DecryptString dispatch Every fixture in the corpus has /StmF and /StrF naming the same /CFM, and every existing test passes the same fileKey/data through both methods, so nothing distinguished DecryptStream from DecryptString: swapping the two constructor assignments survived, and gutting DecryptString to return its input unchanged survived too. Add two tests with deliberately mismatched stream/string filters (Identity/RC4 both ways) plus a direct Identity round trip, since `case Identity: return data.ToArray()` could regress to returning an empty array with the suite still green. * test(kernel): pin the AES-CBC length guard and padding failure data.Length < 16 || (data.Length - 16) % 16 != 0 had no test at all; dropping it wholesale still passed the suite. Add 15- and 31-byte inputs (too short for the IV, and IV-plus-a-partial-block). Also add a wrong-but-legal-size (32-byte) key: the only existing test aimed at the padding-failure catch block actually trips aes.Key's setter on a too-short key, never TransformFinalBlock's own rejection of bad PKCS#7 padding, so moving TransformFinalBlock outside the try block would have passed unnoticed. * test(kernel): sharpen the /P tamper test to a single bit VerifyPermissions_detectsATamperedPValue tampered with info.P ^ -1, flipping all 32 bits, so narrowing the four-byte comparison against /Perms down to a single byte would still pass. Flip one permission bit instead, so the test only passes if all four bytes are compared. * test(kernel): pin the "adb" marker check inside VerifyPermissions Deleting the marker check survived every existing test: the wrong-key tests already fail on an unrelated comparison (garbage plaintext, so /P mismatches too), and the tamper tests only ever corrupt /P or /EncryptMetadata. Build a /Perms block by hand with a correct /P and /EncryptMetadata but a corrupted marker, so the marker check is the only thing that can make it fail. * test(kernel): pin /V, /R and the constructor's length guards `v is < 1 or > 5 or 3` narrowed to `v is 3`, and the /R range check deleted outright, both left every existing test green. Add V=0, V=6, R=1 and R=7 cases. Also fill in five field-length guards that had no test of their own: /U at R<5 (only /O was pinned), keyLengthBytes outside 5-16 at R<5, /O and /U at 48 bytes for R>=5, and keyLengthBytes != 32 for R>=5. The R>=5 /U guard is the sharpest of the five: without it, TryComputeFileKeyFromUserPassword's `_u.AsSpan(32, 8)` on a 32-byte /U throws ArgumentOutOfRangeException from inside the password path instead of failing cleanly up front. * test(kernel): pin the object-key truncation at a non-corpus length min(fileKey.Length + 5, 16) and min(fileKey.Length * 2, 16) agree at every key length this file's other vectors use (5 and 16), so a regression to the second formula would still pass. 7 bytes is the smallest length where they diverge (12 vs. 14), computed independently with Python's hashlib, not by running the code under test. * test(kernel): pin /EncryptMetadata false through write and read /Perms The first test where StandardSecurityHandler.ComputePerms (write) and StandardSecurityDecryptor.VerifyPermissions (read) meet on /Perms with /EncryptMetadata false. Every other R6 /Perms test, in this file and in EncryptionTests, only ever runs with the default true, so ComputePerms hardcoding block[8] = 'T' instead of branching on the setting would survive both suites. * docs(kernel): vary two more repeats of the "not merely/just" shape The new /EncryptMetadata-false test and a CHANGELOG rewording both introduced another instance of the same contrastive phrasing the earlier nits commit was trying to cut down on.
Tim81
added a commit
that referenced
this pull request
Sep 6, 2026
Third and last PR for #97, after the RC4/MD5 primitives (#203) and the decrypt algorithms (#207). Wires them into the reader and ships the public surface. PdfReader.Open(bytes, password) opens Standard-security-handler documents at /V 1, 2, 4 and 5 and /R 2 through 6 — RC4-40 through RC4-128, AES-128 and AES-256 — plus the /Crypt filter and crypt filters naming different methods for strings and streams. Strings are decrypted in Resolve under the identity of the indirect object containing them (ISO 32000-1 §7.6.2, Algorithm 1) and stream bodies on the decode path; ParsedStream.RawBody still holds the verbatim file bytes, which StreamRule and HexStringRule need for byte offsets. Two behavioural breaks, both under Breaking changes in the CHANGELOG. A password-protected document now reaches PdfPreflight as PdfPasswordException, which does not derive from NotSupportedException, so a caller that caught the old UnsupportedPdfFeatureException to detect an encrypted file no longer catches it. And PdfDocument.DocumentId refuses a value that is not 16 bytes, where any other length was previously written as no /ID at all, silently — which produced an encrypted document qpdf rejects outright. A signature dictionary's /Contents is never decrypted. ISO 32000-1 says nothing either way; a signer patches those hex digits into already-serialized bytes, so decrypting them corrupts /ByteRange verification. Measured against qpdf across five signature shapes, and stated in full in the CHANGELOG. Reviewed over ten adversarial rounds. The ninth and earlier each found real defects, among them a cache-poisoning bug that left an object cached as ciphertext, a file key not required to be random, and /U's two salts not required to differ. The tenth found none: three independent reviewers ran 107 mutations, one built a reference implementation of §7.6 from the spec and a 312-file differential corpus, and all 312 open and decrypt correctly. What that round found was five places where the suite was green for the wrong reason, all now joined and each verified to kill its own mutation. Closes #97.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Second of three PRs for #97. This one lands the decrypt algorithms only. The reader wiring and the
public API (
PdfEncryptionInfo, password overloads, removing the/Encryptgate) follow in a third.Nothing user-visible ships:
StandardSecurityDecryptorisinternal, there is noPublicAPI.*.txtchange, and nothing under
src/VellumPdf.Reader/is touched.What it covers
The full matrix the committed corpus exercises: V1/R2 (RC4-40), V2/R3 (RC4 40-128),
V4/R4 with
/CFcrypt filters (/V2and/AESV2), V5/R5 (AES-256, deprecated) andV5/R6 (AES-256). Algorithms 1, 1.A, 2, 2.A, 2.B, 4, 5, 7 and 13, plus per-object key derivation
MD5(fileKey || obj[0..3] || gen[0..2] || sAlT?)truncated tomin(len+5, 16)— which consumes thegeneration number, and is why #121 had to land first.
Hash2B,PasswordBytesandConcatwere promoted from private to internal on the write-side handlerrather than duplicated, so there stays one implementation of each algorithm in the tree.
Why the tests are worth something
Wrong cryptography that round-trips against its own encryptor looks perfect. The check that matters here
is external: for each of the eight qpdf-produced fixtures from #99, object 6's content stream is
decrypted and compared byte-for-byte against
plaintext-baseline.pdf. Agreement with an independentimplementation is the claim; self-consistency would not be.
An adversarial review ran 41 targeted mutations, each with the built assembly's SHA-256 recorded
before and after. 39 killed tests. Of the two survivors, one is a genuine equivalent mutant — reversing
Algorithm 7's 20 RC4 passes is unobservable, because RC4 is XOR against a key-only keystream and
composing the passes is order-independent — and the other was a real blind spot, now closed.
What the review found, and what changed
The cryptography itself was correct; every defect was in the checking layer, the tests or the citations.
Constructor_atRevision5_requiresOeAndUepassed a 32-byte/Oat R6,tripping the length guard before the
/OEcheck was reached. Deleting both the/OEand/UEguards left all 55 tests green. Split in two, each now dies to its own guard.
Algorithm 7's fifty-round loops killed zero tests: no fixture combines R>=3 with a key shorter than
16 bytes. That regression would silently corrupt every 40-120 bit R>=3 file, which real producers emit.
Closed with an independently computed R3 vector at 5 bytes; it is now the only test that mutation kills.
VerifyPermissionscould not detect the tamper its own doc claimed. It never received/Por/EncryptMetadata, so/Pedited to -4, -60, 0 orint.MinValueall passed. qpdf catches this. Now aninstance method comparing both, still advisory and non-gating — which is settled: ISO 32000-2 factors
key retrieval (Algorithm 2.A) from permission validation (Algorithm 13, §7.6.4.4.12) as separate
named algorithms, neither states what a reader shall do on mismatch, and qpdf warns yet still
authenticates and decrypts correctly.
reference to ISO 32000-1 for AESV3, which that edition does not define. A fifth, pre-existing in
ComputePerms, is fixed in its own commit.CryptographicExceptionescaped the reader's vocabulary on a crafted/V 4 /Length 40with/CFM /AESV2, which yields a 10-byte AES key. Contained./V 3was accepted despite the guard's own message listing "1, 2, 4 or 5"; such a file would havebeen treated as V2 RC4 and produced garbage. Rejected now.
Deliberately not changed
R<=4 passwords should be PDFDocEncoding, while
PasswordBytes(correct for the R6 write side) isUTF-8. A password of
caféon an R3 file would then produceC3 A9where other readers produceE9.The corpus uses
"u"and"o", so nothing here can see it. The primary text could not be reached toconfirm — pdfa.org refuses automated fetches and the public sample stops before clause 7.6 — so the
code is unchanged and the open question is recorded in a doc comment rather than acted on from secondary
sources. It becomes live when the reader wiring lands.
Likewise the R5 hash comment: §7.6.4.3.3 is scoped "revision 6 and later" and R5 predates ISO 32000-2
with no clause of its own, so the comment says that instead of citing a plausible number.
Verification
Full solution with
REQUIRE_VERAPDF=1andREQUIRE_BARCODE_ORACLE=1: 4977 passed, 0 failed, 0skipped (Kernel 1242 -> 1305).
dotnet format --verify-no-changesclean,clean-room-check.ps1passes,AOT smoke passes, no tab bytes, no
PublicAPIchange, no released CHANGELOG section altered.Second review round — four reviewers, 48 mutations
Scopes: fix-commit correctness, mutation re-verification, citations, and readiness for the wiring PR. The
cryptography held up again; every finding was a guard, a test, or a claim. 21 items fixed in 12 further
commits, each test gap closed with recorded before/after assembly hashes.
The correction that matters most is not a bug. The owner-key 50-round truncation is right, and
ISO 32000-1 Algorithm 3 step (c) says otherwise — "pass it", where Algorithm 2 step (h) says "pass
the first n bytes". A reviewer built both variants as real R3
/Length 40files: under the literalreading qpdf reports
invalid passwordand popplerIncorrect password; under ours both accept the ownerpassword. Implementations truncate; the text does not say to. Neither comment recorded that, and the test
could not tell the difference — its
/Owas generated with truncation enabled, so it pinned the lengthand not the reading. Both comments now name the deviation and why interoperability wins, so the next
maintainer does not "fix" it and break every 40-120 bit R3 file.
Two questions this PR deferred turned out to be answerable. The Adobe Supplement to ISO 32000
(ExtensionLevel 3) documents the R5 hash as Algorithm 3.2a, and settles R<=4 password encoding as
PDFDocEncoding — not Latin-1, as an earlier version of this description claimed. A reviewer also read
ISO 32000-1 clause 7.6 in full: it says nothing whatsoever about password character encoding. Both are now
cited; the encoding behaviour is unchanged and belongs to the wiring PR, which should try UTF-8 then
PDFDocEncoding.
Fixed:
VerifyPermissionsthrew a rawCryptographicExceptionat R<=4 and returned a meaningless boolean atR4 with a 16-byte key — the same unguarded
aes.Keythat an earlier commit fixed one method over. Nowgated on
_r >= 5 && key.Length == 32.CryptFilterMethodgainsUnsupported, throwingInvalidDataException. Without it,Identityis thenatural fallback for a
/StmFnaming a missing/CFentry — and it returns ciphertext as plaintextwith no error, silently corrupting a whole document.
"§7.6.2 note c"still present twenty lines below where aprevious commit's own message declared it removed.
DecryptStringhad zero coverage andswapping
/StmFwith/StrFsurvived, because every test passed the same method for both and all eightfixtures have
streammethod == stringmethod. Also unpinned: the AES-CBC length guard, the PKCS#7padding path, five constructor length guards, the
"adb"marker, and the object-key truncation formula(pinned at two points that happen to agree). The
/Ptamper test usedP ^ -1, so it pinned one bytewhile appearing to pin four.
ComputePermshardcodingblock[8] = 'T'survived both suites, because the write-side test only ever ran withEncryptMetadata = true. The two sides now meet on/Permsfor the first time.Verification: 4999 passed, 0 failed, 0 skipped with oracles live (Kernel 1242 -> 1327). Format clean,
clean-room passes, AOT smoke passes, no tabs, no
PublicAPIchange, nosrc/VellumPdf.Reader/change.