pyHanko Documentation

repository·master·Indexed 20 days ago

https://github.com/matthiasvalvekens/pyhanko

A Python library and CLI tool for digitally signing, stamping, and validating PDF files. It supports PAdES profiles, Long Term Validation (LTV), and various cryptographic algorithms including RSA, ECDSA, and EdDSA. The suite includes pyhanko-certvalidator for X.509 certificate path validation with CRL/OCSP support, and pyhanko-cli for command-line operations. Key features include PDF 2.0 encryption, difference analysis for incremental updates, and support for PKCS#11.

Tokens
64.7K
Snippets
168
Records
255
Agent score
73%

What's inside pyHanko

  1. Overview of pyHanko features

    master

    pyHanko functions as both a Python library and a command-line tool (distributed via pyhanko-cli). Key capabilities include:

    Stamping

    • Simple text-based stamps and QR stamps.
    • Support for monospaced or embedded TTF/OTF fonts (requires [opentype] dependency).

    Document Preparation

    • Adding empty signature fields to existing PDFs.
    • Adding seed values to signature fields (with or without constraints).
    • Managing document metadata.

    Signing

    • Supports invisible signatures or visible appearances via stamping tools.
    • LTV (Long Term Validation): Supports PAdES baseline profiles B-B, B-T, B-LT, and B-LTA, including Adobe-style revocation info embedding.
    • Algorithms: RSA (PKCS#1 v1.5 and RSASSA-PSS), DSA, ECDSA, EdDSA (Ed25519 and Ed448), and ML-DSA.
    • Integrity: Supports multiple signatures using incremental updates.
    • Advanced Features: RFC 3161 timestamp server support, PKCS#11 support, and an "interrupted signing" mode for remote/interactive processes.

    Signature Validation

    • Cryptographic integrity and X.509 chain of trust validation.
    • Difference analysis for files with multiple signatures or incremental updates.
    • AdES validation and validation against EU trusted lists.

    Encryption

    • Supports PDF 2.0 encryption methods and authenticated encryption (ISO/TS 32003/32004).
    • Supports RSAES-OAEP and ephemeral-static ECDH with X9.63 key derivation.

    CLI & Configuration

    • YAML-based configuration.
    • CLI built on click. Use pyhanko --help for assistance.
  2. Overview of the pyHanko library components

    master

    The pyHanko library is composed of several specialized packages that handle different aspects of PDF manipulation and digital signatures:

    • pyhanko.pdf_utils: A heavily modified version of PyPDF2 used for low-level PDF operations required for signing and validation workflows.
    • pyhanko.sign: The core signature API package. It implements the general logic for both signing and validating digital signatures.
    • pyhanko.stamp: Handles the rendering of signature appearances and the stamping of PDFs.
    • pyhanko.keys: Provides utilities for loading and managing cryptographic keys and certificates.
    • pyhanko_certvalidator: A separate package providing support for certificate validation.
    • pyhanko.config and pyhanko.cli: Thin wrappers for configuration and command-line interface functionality (the latter is packaged as pyhanko-cli). These are primarily intended for the plugin system rather than direct public API usage.
  3. Explore the pyhanko_certvalidator API surface

    master

    The pyhanko_certvalidator package provides tools for certificate validation. The API is organized into several modules and subpackages covering ASN.1 types, authority information, validation contexts, error handling, name trees, path validation, policy trees, and registries.

    Key functional areas include:

    • Validation Logic: Found in pyhanko_certvalidator.validate and pyhanko_certvalidator.sig_validate.
    • Path & Policy: Handled by pyhanko_certvalidator.path, pyhanko_certvalidator.policy_decl, and pyhanko_certvalidator.policy_tree.
    • Data Structures: Managed via pyhanko_certvalidator.asn1_types and pyhanko_certvalidator.name_trees.
    • Revocation & LTV: Supported through subpackages pyhanko_certvalidator.revinfo, pyhanko_certvalidator.ltv, and pyhanko_certvalidator.fetchers.
  4. Explore the pyhanko.pdf_utils package modules

    master

    The pyhanko.pdf_utils package provides a collection of utility modules for low-level and high-level PDF manipulation. Use these modules to handle specific PDF tasks such as barcode generation, image embedding, content manipulation, and incremental writing.

    Subpackages

    • pyhanko.pdf_utils.crypt: Cryptographic utilities.
    • pyhanko.pdf_utils.font: Font manipulation utilities.
    • pyhanko.pdf_utils.metadata: Metadata handling utilities.

    Key Modules

    • barcodes: Barcode generation and handling.
    • content: PDF content stream manipulation.
    • embed: Embedding resources into PDFs.
    • filters: PDF stream filters.
    • form_tools: Tools for working with PDF forms.
    • images: Image processing and handling for PDFs.
    • incremental_writer: Tools for performing incremental updates to PDF files.
    • layout: Layout and positioning utilities.
    • qr: QR code generation and handling.
    • reader / writer: High-level PDF reading and writing interfaces.
    • xref: Cross-reference table manipulation.
  5. Understand the pdf-utils package purpose and limitations

    master

    The pyhanko.pdf_utils package implements the core logic for reading and writing PDF files. It is a specialized PDF toolbox derived from a fork of PyPDF2, optimized for the low-level needs of digital signing.

    Important Warnings:

    • Private API: Most of pyhanko.pdf_utils should be considered a private API. While the internal data model for PDF objects is stable, the text handling and layout code is primitive and subject to change.
    • Unsupported Features: Several stream encoding schemes are not yet supported, most notably LZW compression. Additionally, not all PNG predictors are supported in the Flate decoder/encoder.
    • Image Support: Image support relies on Pillow and currently supports most RGB bitmap types. Other color spaces, native PDF JPEG support, and advanced image compression techniques are not yet implemented.
  6. Understand pyhanko-certvalidator features and capabilities

    master

    The pyhanko-certvalidator library provides comprehensive X.509 path validation, including:

    • Path Building & Validation: Supports RSA (including PSS), DSA, ECDSA, and EdDSA signatures, name chaining, validity dates, basic constraints (CA flag, path length), key usage, and extended key usage.
    • Policy Enforcement: Handles certificate policies, policy constraints, policy mapping, and inhibitAnyPolicy.
    • Revocation Checks: Supports CRLs (including Indirect and Delta CRLs) and OCSP (including delegated responders). It allows for disabling, requiring, or allowing soft failures and supports caching of CRL/OCSP responses.
    • Advanced Validation: Supports point-in-time validation, name constraints, and attribute certificates.
    • Network Clients: Includes HTTP clients for CRL and OCSP retrieval.
  7. Overview of pyHanko release authenticity mechanisms

    master

    PyHanko ensures the integrity of its software supply chain through several layers of verification, using GitHub as the trust root.

    Current Mechanisms (Post-v0.36.0)

    • GitHub Artifact Attestations: Uses GitHub Actions OIDC tokens to produce SLSA build provenance backed by Sigstore. This certifies that artifacts originated from a specific repository, ref, and build workflow.
    • PyPI Trusted Publisher: PyHanko uses PyPI's trusted publisher model, which uploads PEP 740 attestations to PyPI. These are visible via PyPI's integrity API.
    • Deployment Environment Verification: The release pipeline uses gated GitHub environments (build-release for building and release for publishing). The environment name is encoded in the signing certificate as a Fulcio X.509 extension (OID 1.3.6.1.4.1.57264.1.23), allowing users to verify that an artifact was produced in a genuine production environment.

    Legacy Mechanisms (v0.36.0 and earlier)

    • Sigstore bundles: *.sigstore.json files verifiable with the sigstore Python package.
    • SLSA provenance: multiple.intoto.jsonl files verifiable with slsa-verifier.

    Warning: PGP signing of releases has been discontinued.

  8. Use PdfContent for PDF graphics and resource management

    master

    The pyhanko.pdf_utils.content module provides the PdfContent class, a bare-bones abstraction for handling content that compiles down to PDF graphics operators.

    PdfContent handles PDF resource management boilerplate and allows you to encapsulate content into form XObjects. Developers can implement their own PdfContent subclasses to define custom graphics or content behaviors.

  9. Handling complex signature appearance requirements

    master
    The built-in signature appearance generation in pyHanko is primitive and focused primarily on the signing process. If you have specific layout requirements or if the default appearance generation does not meet your needs, you should consider "outsourcing" the appearance generation to a more capable graphics toolkit. Refer to the documentation on static content stamps for guidance on this approach.
  10. Understand pyHanko CLI command structure

    master

    The pyHanko CLI is built using the Click library and uses a subcommand-based architecture.

    Key behaviors:

    • Help: Use pyhanko --help to access built-in help documentation.
    • Subcommand Groups: The CLI is organized into groups, primarily sign (for signing) and stamp (for stamping).
    • Option Placement: Because of the Click implementation, the position of parameters is important. Double-dash options (e.g., --option) should generally be placed after the subcommand they apply to, but before any subsequent subcommands.
  11. Extend the Signer class

    master

    If you need to implement a custom signing device or technique (e.g., AWS KMS, a hardware token, or a custom protocol), you can extend the Signer class.

    • To implement a new signing technique: Implement Signer.async_sign_raw. This method computes the raw cryptographic signature of data (typically a document hash) and accepts a dry_run flag (where the returned object has the correct size but content is irrelevant).
    • To modify CMS object structure: Override Signer.async_sign, which is responsible for the construction of the CMS object itself.