Skip to main content

django-pdf-sign

Клиентские электронные подписи PDF-документов в Django.

Сервер никогда не хранит закрытые ключи. Он подготавливает PDF с видимым штампом, передаёт браузеру точные байты для подписи (плагин КриптоПро), проверяет присланную отсоединённую CMS и встраивает её в документ.

  • ГОСТ Р 34.10-2012 / CAdES-BES — квалифицированные подписи (Стрибог-256/512), проверяемые российскими валидаторами при наличии квалифицированного сертификата.
  • PAdES / RSA-ECDSA — подписи, совместимые с Adobe.

Установка

pip install django-pdf-sign

Серверу не нужен КриптоПро: проверка выполняется библиотеками gostcrypto и cryptography.

Быстрый старт

# settings.py
INSTALLED_APPS = [
    # ...
    "django.contrib.contenttypes",
    "django_pdf_sign",
]
from django_pdf_sign.services import prepare_signing, complete_signing

# Шаг 1: браузер присылает сертификат, сервер готовит документ.
prepared = prepare_signing(
    document=invoice,
    user=request.user,
    certificate_der=certificate_der,  # DER-сертификат из браузера
    page=-1,                           # последняя страница
    box=(57, 57, 284, 170),            # 80x40 мм, отступы 20 мм
)

# Шаг 2: отдать браузеру.
response = {
    "session_id": str(prepared.session.pk),
    "bytes_to_sign": base64.b64encode(prepared.bytes_to_sign).decode(),
    "digest_algorithm": prepared.digest_algorithm,
    "expires_at": prepared.expires_at.isoformat(),
}

# Шаг 3: браузер вернул отсоединённую CMS — проверить и встроить.
result = complete_signing(
    session_id=prepared.session.pk,
    cms=cms_bytes,
    user=request.user,
)
result.signed_pdf      # байты подписанного PDF
result.record          # неизменяемая запись аудита

Что делает пакет

  • Добавляет поле подписи и штамп в российском стиле.
  • Возвращает точные байты /ByteRange для подписи.
  • Проверяет, что CMS покрывает именно эти байты, сертификат совпадает с сессией, а подпись криптографически верна.
  • Встраивает CMS, сохраняет подписанный PDF и пишет запись аудита.
  • Проверяет цепочку сертификатов, отзыв (CRL и OCSP) и метки времени CAdES-T, если задана политика.
  • Помечает и удаляет брошенные сессии (python manage.py pdf_sign_cleanup).

Чего пакет не делает

  • Не хранит, не принимает и не журналирует закрытые ключи, PIN и контейнеры.
  • Не является удостоверяющим центром и не выдаёт сертификаты.
  • Не заменяет сертифицированное СКЗИ на стороне подписанта.
  • Не даёт юридическую силу сам по себе: нужны квалифицированный сертификат и сертифицированное СКЗИ. Подробности в docs/legal.md.

Настройки

DJANGO_PDF_SIGN = {
    "SESSION_TTL": 900,
    "BYTES_RESERVED": 16384,
    "MAX_DOCUMENT_BYTES": 25 * 1024 * 1024,
    "DEFAULT_PAGE": -1,
    "DEFAULT_BOX": (57, 57, 284, 170),
    "SUBFILTER": None,
    "STAMP": {
        "TEXT": "...",
        "FONT_PATH": None,
        "FONT_SIZE": 7,
        "BORDER_WIDTH": 1,
        "BACKGROUND_PATH": None,
    },
    "VERIFY": {
        "CHECK_CHAIN": False,
        "TRUST_ROOTS": (),
        "INTERMEDIATE_CERTS": (),
        "CRLS": (),
        "OCSPS": (),
        "REVOCATION_MODE": "soft-fail",  # none | soft-fail | require
        "ALLOW_FETCHING": False,
        "FETCH_ALLOWED_HOSTS": (),
        "CHECK_TIMESTAMPS": False,
        "REQUIRE_TIMESTAMP": False,
    },
    "PREPARED_UPLOAD_TO": "django_pdf_sign/prepared/%Y/%m/%d",
    "SIGNED_UPLOAD_TO": "django_pdf_sign/signed/%Y/%m/%d",
    "ON_EVENT": None,
}

Пути к корневым сертификатам, CRL и ответам OCSP — строки, файлы читаются при создании политики.

Документация

Требования

  • Python 3.11+
  • Django 5.2 LTS, 6.0 или 6.1 (Django 4.2 не поддерживается)
  • pyhanko[opentype], asn1crypto, cryptography, gostcrypto

Разработка

uv sync --all-extras
uv run pytest
uv run ruff check .
uv run ruff format --check .
uv run python -m mypy
uv build

Лицензия

MIT. Встроенный шрифт DejaVu Sans распространяется по лицензии Bitstream Vera; см. src/django_pdf_sign/fonts/LICENSE.DejaVu.

Metadata

Release files for django-pdf-sign 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-pdf-sign 1.0.0
File Size Uploaded Provenance Actions
django_pdf_sign-1.0.0.tar.gz 511.4 kB With provenance Details for django_pdf_sign-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-pdf-sign 1.0.0
File Interpreter ABI Platform Actions
django_pdf_sign-1.0.0-py3-none-any.whl Python 3 none any Details for django_pdf_sign-1.0.0-py3-none-any.whl

Total release size: 943.6 kB

Release files / django_pdf_sign-1.0.0.tar.gz

Download URL django_pdf_sign-1.0.0.tar.gz
Size 511.4 kB
Tags Source
SHA-256 checksum
How to use checksums
dbb5c681b8f8fcf3a4eae80471017e117d787b9fbce33264bcfecec78b9aeb42
BLAKE2b-256 checksum
How to use checksums
2b4d8a564a7f641095fc52bcc4ba38d77ce8e626966efb622786ec293b1108f6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 8, 2026.

Transparency log

Release files / django_pdf_sign-1.0.0-py3-none-any.whl

Download URL django_pdf_sign-1.0.0-py3-none-any.whl
Size 432.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fe6531d1ac4ab46838ac80d1d89a247c1e6b9dd10fd2551a78ab1123ef6268de
BLAKE2b-256 checksum
How to use checksums
6c75fcd8d66d7a865ff4893a8eeff36d18ba837774c48ed6e3eece8dcf4693ab
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 8, 2026.

Transparency log

Security for django-pdf-sign 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for django_pdf_sign-1.0.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 8, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page