pdf_cos library

COS (Carousel Object System) layer: the PDF file format's object model, tokenizer, parser, filters, cross-reference machinery, and serializer.

Classes

Aes
AES block cipher (FIPS 197) with the CBC modes PDF encryption needs (§7.6.2, §7.6.4.3): content decryption (16-byte IV prefix, PKCS#7 padding) and the unpadded CBC encryption inside the AES-256 password hash (Algorithm 2.B). Pure Dart so it runs on the VM and the web.
Ascii85Filter
AsciiHexFilter
CcittDecoder
The decoder itself, usable directly (the JBIG2 MMR path reuses it).
CcittFaxFilter
CCITTFaxDecode (§7.4.6): ITU-T T.4 (Group 3, 1-D and 2-D) and T.6 (Group 4) fax compression, the workhorse of scanned monochrome PDFs.
CertificateChainResult
The outcome of X.509 path building and verification.
CertificateRevocationList
A parsed CertificateList. der keeps the original bytes for verbatim embedding in a /DSS /CRLs array.
CmsSignedData
CmsSignerInfo
CmsVerification
Outcome of verifying one CMS signer against detached content bytes.
ContentOperation
One content-stream instruction: operands followed by an operator.
ContentOperationCursor
Incremental reader for a flat PDF content stream.
ContentStreamParser
Parses a page content stream into a flat list of operations.
ContentStreamSerializer
Serializes parsed content-stream operations back to PDF content syntax.
CosArray
CosBoolean
CosCompactionResult
The outcome of a CosCompactor run: the rewritten bytes plus a small before/after accounting so hosts can report "saved N%".
CosCompactor
Rewrites a CosDocument into a fresh, compacted PDF - the lossless structural pass of the file-size optimiser (#368).
CosDictionary
CosDocument
A parsed PDF file at the COS level: header, cross-reference machinery, and on-demand object loading. Page-level semantics live in pdf_document.
CosDocumentBuilder
Assembles a brand-new PDF file from scratch - the counterpart of CosIncrementalUpdater for output that does not extend an existing byte stream (extracted page ranges, merged documents, generated files).
CosFilter
Decodes one stage of a stream's /Filter chain.
CosIncrementalUpdater
Writes changes to a document as an incremental update: the original bytes are preserved verbatim and changed objects plus a new cross-reference section are appended (§7.5.6). This keeps existing digital signatures valid and makes every edit reversible.
CosIndirectObject
A numbered object as it appears in the file body: N G obj ... endobj.
CosInteger
CosLexer
Tokenizer for PDF syntax (ISO 32000-1 §7.2).
CosName
CosNull
CosObject
Base class for every value in a PDF file's object graph (ISO 32000-1 §7.3).
CosParser
Parses COS objects from a byte buffer.
CosReal
CosReference
An indirect reference, e.g. 12 0 R.
CosSerializer
Serializes COS objects back to PDF syntax.
CosSourceOpenResult
The document and completeness metadata produced by a source open.
CosStream
CosString
A PDF string is a sequence of bytes, not characters.
CosToken
CosTokenBuffer
Mutable token storage for allocation-sensitive streaming parsers.
CosXrefChain
The merged view of a walked cross-reference chain: every object number mapped to the entry from the newest section that defines it, plus the newest section's trailer and the startxref the walk began at.
CosXrefEntry
One cross-reference entry: where to find an object.
CosXrefReader
Reads a document's cross-reference machinery over a byte buffer: locating startxref, parsing a single section (classic xref table or a /XRef stream, with /W widths and /Index ranges), and walking the /Prev+/XRefStm chain newest-to-oldest into one merged CosXrefChain view.
CosXrefSection
One parsed cross-reference section (a table or stream) and its trailer.
CosXrefTableWriter
Writes the file-tail framing shared by the from-scratch CosDocumentBuilder and the incremental CosIncrementalUpdater: the classic cross-reference table (entry encoding plus consecutive-run subsections), the trailer dictionary, and the startxref/%%EOF epilogue.
CrlEntry
One revoked entry: the certificate serial and when it was revoked.
DerObject
One parsed DER value: identifier octet, content octets, and the full encoded byte range (needed when a signature is computed over the exact encoding of a sub-structure).
DerTag
Universal tag numbers this library cares about.
DigestOid
Digest algorithm OIDs paired with their DigestInfo prefixes.
EcCurve
A short-Weierstrass prime curve y² = x³ + ax + b (mod p).
EcPrivateKey
An EC private key: a scalar d on curve. The public key is d·G.
EcPublicKey
FlateFilter
FlateDecode: zlib/deflate, optionally followed by a PNG/TIFF predictor.
Jbig2Decoder
JBIG2 decoder for the PDF embedded profile (§7.4.7, ITU-T T.88).
JpxDecoder
JPEG 2000 decoder (ITU-T T.800) for PDF JPXDecode streams.
JpxImage
A decoded JPEG 2000 image: 8-bit samples, components interleaved.
LzwFilter
LZWDecode (§7.4.4): TIFF-style LZW with 9–12 bit codes packed MSB-first, optionally followed by a PNG/TIFF predictor.
OcspOid
OcspResponse
A parsed OCSP response. der keeps the original bytes for embedding the response verbatim in a /DSS /OCSPs array.
OcspSingleResponse
One SingleResponse inside a BasicOCSPResponse.
PdfBytesByteSource
A PdfByteSource backed by a complete in-memory buffer. Handy for tests and for adapting already-downloaded bytes to the source-based API.
PdfByteSource
A random-access, possibly asynchronous source of PDF bytes.
PdfMatrix
A 2D affine transform in PDF convention: row vectors, so a point maps as x' = a·x + c·y + e, y' = b·x + d·y + f (ISO 32000-1 §8.3.3).
PdfSourceLoadOptions
Tuning knobs for openCosDocumentFromSource. The defaults suit HTTP Range loading: a few KB probes for the header, ~64 KB windows for the tail and each xref section, and coalescing of nearby object ranges so densely packed bodies fetch in one request instead of thousands.
RsaPrivateKey
RsaPublicKey
RunLengthFilter
RunLengthDecode (§7.4.5): length byte 0–127 copies the next length+1 bytes literally; 129–255 repeats the next byte 257−length times; 128 is EOD.
StandardSecurityHandler
The standard security handler (§7.6.4): authenticates a password and decrypts strings and streams.
TimeStampToken
A parsed RFC 3161 timestamp token: the CMS wrapper plus the decoded TSTInfo it signs.
TimeStampVerification
The outcome of verifying a timestamp token against the data it stamps.
TspOid
TstMessageImprint
The MessageImprint of a TSTInfo - the digest the token attests to.
X509Certificate

Enums

CosTokenType
CosXrefEntryType
OcspCertStatus
OcspResponseStatus
PdfCipher
Which cipher a class of content (strings or streams) uses.
TspStatus
PKIStatus values that matter to a caller (RFC 3161 §2.4.2).

Functions

applyPredictor(Uint8List data, CosDictionary? params) Uint8List
Reverses the /Predictor transform described by a filter's /DecodeParms (ISO 32000-1 §7.4.4.4). Returns data unchanged when no predictor is set.
buildCaCertificate({required EcPrivateKey key, required String commonName, String? organization, required DateTime notBefore, required DateTime notAfter, int? pathLength, BigInt? serialNumber, Random? random, Hash hash = crypto.sha256}) Uint8List
Builds a self-signed X.509 v3 CA certificate for key - the root of an "org CA" a deployment issues member signing certs from (see issueCertificate). Carries basicConstraints cA=TRUE (with an optional pathLength) and a keyUsage of keyCertSign + cRLSign. Share its DER as a trust anchor; member certificates then chain to it and validate.
buildOcspRequest({required X509Certificate cert, required X509Certificate issuer, Hash hash = crypto.sha1, BigInt? nonce}) Uint8List
Builds the DER OCSPRequest (RFC 6960 §4.1.1) asking whether cert, issued by issuer, is revoked. The CertID is keyed by the issuer name hash, issuer key hash, and the certificate serial. hash is the CertID digest (SHA-1 is still what most responders key on). An optional nonce is echoed by the responder.
buildSelfSignedCertificate({required EcPrivateKey key, required String commonName, String? organization, String? email, required DateTime notBefore, required DateTime notAfter, BigInt? serialNumber, Random? random, Hash hash = crypto.sha256}) Uint8List
Builds a self-signed X.509 v3 certificate for key, returning its DER.
buildTimeStampRequest({required List<int> messageImprint, Hash hash = crypto.sha256, BigInt? nonce, bool requestCertificate = true, String? reqPolicy}) Uint8List
Builds the DER TimeStampReq (RFC 3161 §2.4.1) that asks a TSA to stamp messageImprint - the digest, computed with hash, of the bytes to be timestamped (for a signature timestamp this is the hash of the signer's signature value; for a document timestamp it is the hash of the signed byte ranges).
cmsAssembleSignedData({required Uint8List signedAttributes, required Uint8List signature, required List<Uint8List> certificates, Hash hash = crypto.sha256, List<Uint8List> unsignedAttributes = const [], String eContentType = _Oid.data, Uint8List? eContent, Uint8List? signatureAlgorithm}) Uint8List
Assembles a detached CMS SignedData from a signedAttributes blob (the SET OF from cmsSignedAttributes) and the RSA signature over it. certificates is the DER chain, signer first. unsignedAttributes (e.g. a signature-time-stamp) are carried in the SignerInfo's 1 field. hash is the digest algorithm named in digestAlgorithms and the SignerInfo (it must match what produced the message digest / signature).
cmsSignatureTimeStampAttribute(Uint8List timeStampToken) Uint8List
The signature-time-stamp unsigned attribute (RFC 3161 / ETSI) wrapping a bare RFC 3161 timeStampToken (a ContentInfo). Goes in a SignerInfo's unsigned-attributes set to lift a CAdES/PAdES signature from B-B to B-T.
cmsSignDetached({required List<int> contentDigest, required RsaPrivateKey privateKey, required List<Uint8List> certificates, DateTime? signingTime, X509Certificate? essCertificate, Hash hash = crypto.sha256}) Uint8List
Builds a detached CMS SignedData over content whose digest is contentDigest, signing with RSA PKCS#1 v1.5. certificates is the DER chain, signer certificate first. Pass essCertificate (normally the signer cert) to add the ESS signing-certificate-v2 attribute that makes the result a CAdES/PAdES baseline signature.
cmsSignDetachedEcdsa({required List<int> contentDigest, required EcPrivateKey privateKey, required List<Uint8List> certificates, DateTime? signingTime, X509Certificate? essCertificate, Hash hash = crypto.sha256}) Uint8List
Like cmsSignDetached but signs the attributes with ECDSA - the path a self-signed P-256 identity takes. The SignerInfo carries the ecdsa-with-SHAx signature algorithm and the DER SEQUENCE { r, s } signature value.
cmsSignedAttributes({required List<int> contentDigest, DateTime? signingTime, X509Certificate? essCertificate, Hash hash = crypto.sha256, String contentType = _Oid.data, List<Uint8List> extra = const []}) Uint8List
The DER SET OF signed attributes the CMS signature is computed over: content-type, message-digest (= contentDigest), optional signing-time, optional ESS signing-certificate-v2 (pass essCertificate for a PAdES baseline), and any extra attributes already DER-encoded as Attribute SEQUENCEs. hash selects the cert-hash and is matched to the message digest algorithm by the caller.
cmsSignEncapsulated({required Uint8List eContent, required String eContentType, required RsaPrivateKey privateKey, required List<Uint8List> certificates, Hash hash = crypto.sha256, DateTime? signingTime}) Uint8List
Builds a CMS SignedData that encapsulates eContent (content type eContentType), signing it with RSA PKCS#1 v1.5. This is the form used by RFC 3161 timestamp tokens (eContentType id-ct-TSTInfo) and other attribute certificates. The content-type signed attribute is set to eContentType as RFC 5652 §11.1 requires.
cmsVerify(CmsSignedData cms, CmsSignerInfo signer, List<int> content) CmsVerification
Verifies signer over the detached content. For encapsulated variants pass the eContent as content override semantics handled by the caller.
decodeStream(CosStream stream, {CosResolver? resolve, String? stopBeforeFilter}) Uint8List
Decodes a stream's payload by applying its /Filter chain in order.
derBitString(List<int> bytes) Uint8List
BIT STRING with no unused trailing bits (the only form PKIX uses here).
derBoolean(bool value) Uint8List
derContext(int n, List<int> content) Uint8List
Context-specific constructed value n wrapping raw encoded content.
derContextPrimitive(int n, List<int> content) Uint8List
Context-specific primitive value n carrying raw content octets.
derEncode(int tag, List<int> content) Uint8List
derEnumerated(int value) Uint8List
ENUMERATED, same content form as INTEGER.
derGeneralizedTime(DateTime time) Uint8List
GeneralizedTime in the DER canonical form (always UTC, seconds present, no fractional part) - what RFC 5280 §4.1.2.5.2 and RFC 3161 require.
derInteger(BigInt value) Uint8List
derNull() Uint8List
derOctetString(List<int> bytes) Uint8List
derOid(String dotted) Uint8List
derSequence(List<List<int>> parts) Uint8List
derSet(List<List<int>> parts) Uint8List
derSetOf(List<Uint8List> parts) Uint8List
SET OF with the DER-mandated sort of element encodings.
derUtcTime(DateTime time) Uint8List
digestOidForHash(Hash hash) String?
Maps a digest hash to its bare AlgorithmIdentifier OID, or null for an unsupported hash. Public companion to the internal _digestOidFor.
ecdsaSign(EcPrivateKey key, List<int> digest, {Hash hash = crypto.sha256}) Uint8List
Signs digest with key, returning the signature as DER SEQUENCE { r, s } (what ecdsaVerify, CMS, and X.509 expect).
ecdsaSignatureAlgorithm(Hash hash) Uint8List
The ecdsa-with-SHAx AlgorithmIdentifier for hash - a bare OID, with no parameters, exactly as RFC 5758 §3.2 specifies for ECDSA.
ecdsaSignRs(EcPrivateKey key, List<int> digest, {Hash hash = crypto.sha256}) → (BigInt, BigInt)
The raw (r, s) scalars, exposed for the RFC 6979 known-answer tests.
ecdsaVerify(EcPublicKey key, List<int> digest, Uint8List signatureDer) bool
Verifies an ECDSA signature (DER SEQUENCE { r, s }) over digest.
ecSubjectPublicKeyInfo(EcPublicKey key) Uint8List
The DER SubjectPublicKeyInfo for an EC public key: an AlgorithmIdentifier of id-ecPublicKey + the named-curve OID, then the uncompressed SEC1 point in a BIT STRING. This is the structure an X.509 certificate carries and the body a PKIX PUBLIC KEY PEM block wraps - e.g. the public key a Fulcio signingCert request sends.
essSigningCertificateV2Attribute(X509Certificate cert, {Hash hash = crypto.sha256}) Uint8List
The ESS signing-certificate-v2 signed attribute (RFC 5035) binding the signature to cert: SigningCertificateV2 with one ESSCertIDv2 holding the certificate hash and its issuer/serial. This is what lifts a CMS signature to a PAdES/CAdES baseline (the signer commits to which certificate signed). hash is the cert-hash algorithm (sha256 default, for which the AlgorithmIdentifier is omitted per the ASN.1 DEFAULT).
hashForDigestOid(String oid) → Hash?
Maps a digest (or combined signature) OID to its crypto.Hash.
issueCertificate({required EcPrivateKey issuerKey, required Uint8List issuerCertificate, required EcPublicKey subjectPublicKey, required String commonName, String? organization, String? email, required DateTime notBefore, required DateTime notAfter, BigInt? serialNumber, Random? random, Hash hash = crypto.sha256}) Uint8List
Issues an end-entity signing certificate for subjectPublicKey, signed by issuerKey and chaining to issuerCertificate (a CA built with buildCaCertificate). The issuer Name is copied from the CA certificate's subject, and an authorityKeyIdentifier links the two. Pair the returned leaf with the CA certificate as the chain of a signing identity.
openCosDocumentFromSource(PdfByteSource source, {String password = '', PdfSourceLoadOptions options = const PdfSourceLoadOptions()}) Future<CosDocument>
Opens a CosDocument from an asynchronous source, fetching only the bytes it needs.
openCosDocumentFromSourceWithStatus(PdfByteSource source, {String password = '', PdfSourceLoadOptions options = const PdfSourceLoadOptions()}) Future<CosSourceOpenResult>
Opens source like openCosDocumentFromSource and reports whether the returned document is an intentionally limited first-paint buffer.
pemBytes(String pem) Uint8List
Strips a PEM armor and decodes the base64 body.
pemEncode(String label, List<int> der) String
Wraps der in a PEM -----BEGIN [label]----- block, the base64 body hard-wrapped at 64 columns (RFC 7468). The inverse of pemBytes.
rc4(List<int> key, Uint8List data) Uint8List
RC4 stream cipher, as used by PDF security handlers up to revision 4 (§7.6.2). Encryption and decryption are the same operation.
rsaSign(RsaPrivateKey key, String digestOid, List<int> digest) Uint8List
Produces a PKCS#1 v1.5 signature over a precomputed digest.
rsaVerify(RsaPublicKey key, String digestOid, List<int> digest, List<int> signature) bool
Verifies a PKCS#1 v1.5 signature over a precomputed digest.
rsaVerifyPss(RsaPublicKey key, Hash hash, List<int> mHash, List<int> signature, {int? saltLength}) bool
Verifies an RSASSA-PSS signature (RFC 8017 §8.1.2) over a precomputed message hash mHash. hash is used both for the message digest and as the MGF1 hash - PSS permits them to differ, but conformant signers (and every real PDF signature) use one algorithm for both.
timeStampTokenFromResponse(Uint8List responseDer) Uint8List
Extracts the bare TimeStampToken (the inner CMS ContentInfo) from a TSA's TimeStampResp. Throws when the TSA rejected the request. The returned bytes are exactly what is embedded in a PDF (the DocTimeStamp /Contents, or the signature-time-stamp attribute value).
verifyCertificateChain({required X509Certificate leaf, List<X509Certificate> intermediates = const [], required List<X509Certificate> trustAnchors, DateTime? at}) CertificateChainResult
Builds and verifies the path from leaf to one of trustAnchors, using intermediates (typically the other certificates shipped in the CMS container) to fill the middle. at is the moment each certificate must be valid - pass the signing time; null skips the validity-window check.
verifyTimeStampToken(TimeStampToken token, List<int> stampedData) TimeStampVerification
Verifies token against stampedData - the exact bytes whose digest the token should attest to (the signature value for a signature timestamp, the signed byte ranges for a document timestamp). Confirms the embedded MessageImprint matches and the TSA's CMS signature is cryptographically valid against its embedded certificate. Trust in the TSA certificate is the caller's to establish (via a trust store) and is out of scope here.

Typedefs

CosResolver = CosObject Function(CosReference ref)
Resolves an indirect reference to its object. The parser needs this when a stream's /Length is itself an indirect reference.
PdfSourceProgress = void Function(int fetched, int? total)
Reports progressive-load progress. fetched is the running total of bytes pulled from the source; total is the document length when known.

Exceptions / Errors

CosParseException
Error while parsing PDF syntax.
CosPasswordException
The document is encrypted and the supplied password (often the empty default) opens neither the user nor the owner door.
UnsupportedEncryptionException
The document uses an encryption scheme this library cannot decrypt (a non-standard security handler, or an unknown crypt filter method).
UnsupportedFilterException
A stream uses a /Filter this library cannot decode yet.