CodeSampleX

Sample

cryptography 41.0.7: exceptions.InvalidTag

Verified sample for pypi cryptography 41.0.7: exceptions.InvalidTag. The contract ran on python 3.12 · linux debian/x64 · docker and passed.

sha256:f5553257def4021954d3db48fd52d62091596df414d61c6ff543281fc3dec329

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
1
Signing keys that built it
1
Declared environment linux 24 · ubuntu · glibc 2.39 x64 pip

Verification-run environments

Environment Contract Stages Run
python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104…
2026-09-13

Case

HOW
Goal
verify cryptography.exceptions.InvalidTag in pkg:pypi/cryptography@41.0.7
Packages
Symbols
  • cryptography.exceptions.InvalidTag
Created
2026-09-13T19:16:53Z

Contract

  1. InvalidTag is an Exception subclass indicating AEAD authentication verification failure
  2. InvalidTag is raised by AESGCM.decrypt when ciphertext or tag payload is corrupted or truncated
  3. InvalidTag is raised by AESGCM.decrypt when associated data does not match the encryption context
  4. InvalidTag is raised by ChaCha20Poly1305.decrypt when authentication verification fails on modified ciphertext

Files

  • PROMPT.md
  • csx.json
  • pyproject.toml
  • requirements.txt
  • sample.py
  • spec.json
  • test/contract.py

Download the source artifact (tar.gz)

Source

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify cryptography.exceptions.InvalidTag in pkg:pypi/cryptography@41.0.7
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/cryptography@41.0.7
Demonstrate these symbols/APIs:
  - cryptography.exceptions.InvalidTag

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:6fdebd394b0a2562ef2f05c9321393e20a7730fc77c9531d8f5a83e7197cc996","contract":["InvalidTag is an Exception subclass indicating AEAD authentication verification failure","InvalidTag is raised by AESGCM.decrypt when ciphertext or tag payload is corrupted or truncated","InvalidTag is raised by AESGCM.decrypt when associated data does not match the encryption context","InvalidTag is raised by ChaCha20Poly1305.decrypt when authentication verification fails on modified ciphertext"],"goal":"verify cryptography.exceptions.InvalidTag in pkg:pypi/cryptography@41.0.7","kind":"HOW","packages":["pkg:pypi/cryptography@41.0.7"],"schemaVersion":1,"symbols":["cryptography.exceptions.InvalidTag"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/cryptography@41.0.7"],"schemaVersion":1,"subject":"pkg:pypi/cryptography@41.0.7","symbols":["cryptography.exceptions.InvalidTag"],"verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "verify-cryptography-invalid-tag"
version = "0.1.0"
dependencies = [
    "cryptography==41.0.7",
]
requirements.txt
cryptography==41.0.7
sample.py
"""Demonstration of cryptography.exceptions.InvalidTag handling with AEAD ciphers."""

from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives.ciphers.aead import AESGCM, ChaCha20Poly1305


def encrypt_aes_gcm(
    key: bytes, nonce: bytes, plaintext: bytes, associated_data: bytes
) -> bytes:
    """Encrypt plaintext using AESGCM, returning combined ciphertext and authentication tag."""
    aesgcm = AESGCM(key)
    return aesgcm.encrypt(nonce, plaintext, associated_data)


def decrypt_aes_gcm(
    key: bytes, nonce: bytes, ciphertext: bytes, associated_data: bytes
) -> bytes:
    """Decrypt ciphertext and verify authentication tag using AESGCM.

    Raises:
        InvalidTag: If ciphertext is corrupted, truncated, or associated data mismatches.
    """
    aesgcm = AESGCM(key)
    return aesgcm.decrypt(nonce, ciphertext, associated_data)


def encrypt_chacha20_poly1305(
    key: bytes, nonce: bytes, plaintext: bytes, associated_data: bytes
) -> bytes:
    """Encrypt plaintext using ChaCha20Poly1305, returning combined ciphertext and tag."""
    chacha = ChaCha20Poly1305(key)
    return chacha.encrypt(nonce, plaintext, associated_data)


def decrypt_chacha20_poly1305(
    key: bytes, nonce: bytes, ciphertext: bytes, associated_data: bytes
) -> bytes:
    """Decrypt ciphertext and verify tag using ChaCha20Poly1305.

    Raises:
        InvalidTag: If ciphertext is corrupted, truncated, or associated data mismatches.
    """
    chacha = ChaCha20Poly1305(key)
    return chacha.decrypt(nonce, ciphertext, associated_data)
spec.json
{
  "schemaVersion": 1,
  "goal": "verify cryptography.exceptions.InvalidTag in pkg:pypi/cryptography@41.0.7",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/cryptography@41.0.7"
  ],
  "symbols": [
    "cryptography.exceptions.InvalidTag"
  ]
}
test/contract.py
"""Contract verification test for cryptography.exceptions.InvalidTag in pkg:pypi/cryptography@41.0.7."""

import os
import sys

# Ensure project root is on sys.path for local module imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives.ciphers.aead import AESGCM, ChaCha20Poly1305
from sample import (
    encrypt_aes_gcm,
    decrypt_aes_gcm,
    encrypt_chacha20_poly1305,
    decrypt_chacha20_poly1305,
)


def test_invalid_tag_is_exception() -> None:
    """Assertion: InvalidTag is an Exception subclass indicating AEAD authentication verification failure."""
    assert issubclass(InvalidTag, Exception), "InvalidTag must be a subclass of Exception"
    err = InvalidTag()
    assert isinstance(err, Exception)


def test_aes_gcm_invalid_tag_on_corrupted_ciphertext() -> None:
    """Assertion: InvalidTag is raised by AESGCM.decrypt when ciphertext or tag payload is corrupted or truncated."""
    key = AESGCM.generate_key(bit_length=256)
    nonce = os.urandom(12)
    plaintext = b"sensitive payload data"
    aad = b"authenticated header"

    ciphertext = encrypt_aes_gcm(key, nonce, plaintext, aad)

    # Legitimate decryption succeeds
    decrypted = decrypt_aes_gcm(key, nonce, ciphertext, aad)
    assert decrypted == plaintext

    # Tampered ciphertext payload raises InvalidTag
    corrupted_ct = bytearray(ciphertext)
    corrupted_ct[0] ^= 0x01
    raised = False
    try:
        decrypt_aes_gcm(key, nonce, bytes(corrupted_ct), aad)
    except InvalidTag:
        raised = True
    assert raised, "Corrupted ciphertext must raise InvalidTag"

    # Tampered tag (last 16 bytes) raises InvalidTag
    corrupted_tag = bytearray(ciphertext)
    corrupted_tag[-1] ^= 0x01
    raised = False
    try:
        decrypt_aes_gcm(key, nonce, bytes(corrupted_tag), aad)
    except InvalidTag:
        raised = True
    assert raised, "Corrupted authentication tag must raise InvalidTag"

    # Truncated ciphertext (missing tag bytes) raises InvalidTag
    truncated_ct = ciphertext[:-8]
    raised = False
    try:
        decrypt_aes_gcm(key, nonce, truncated_ct, aad)
    except InvalidTag:
        raised = True
    assert raised, "Truncated ciphertext must raise InvalidTag"


def test_aes_gcm_invalid_tag_on_mismatched_aad() -> None:
    """Assertion: InvalidTag is raised by AESGCM.decrypt when associated data does not match the encryption context."""
    key = AESGCM.generate_key(bit_length=256)
    nonce = os.urandom(12)
    plaintext = b"confidential records"
    aad = b"valid_auth_context"

    ciphertext = encrypt_aes_gcm(key, nonce, plaintext, aad)

    # Mismatched associated data raises InvalidTag
    raised = False
    try:
        decrypt_aes_gcm(key, nonce, ciphertext, b"mismatched_auth_context")
    except InvalidTag:
        raised = True
    assert raised, "Mismatched associated data must raise InvalidTag"

    # Empty associated data when non-empty was used raises InvalidTag
    raised = False
    try:
        decrypt_aes_gcm(key, nonce, ciphertext, b"")
    except InvalidTag:
        raised = True
    assert raised, "Missing associated data must raise InvalidTag"


def test_chacha20_poly1305_invalid_tag_on_tampering() -> None:
    """Assertion: InvalidTag is raised by ChaCha20Poly1305.decrypt when authentication verification fails on modified ciphertext."""
    key = ChaCha20Poly1305.generate_key()
    nonce = os.urandom(12)
    plaintext = b"chacha20 payload"
    aad = b"metadata"

    ciphertext = encrypt_chacha20_poly1305(key, nonce, plaintext, aad)

    # Legitimate decryption succeeds
    decrypted = decrypt_chacha20_poly1305(key, nonce, ciphertext, aad)
    assert decrypted == plaintext

    # Tampered ciphertext raises InvalidTag
    corrupted_ct = bytearray(ciphertext)
    corrupted_ct[0] ^= 0xFF
    raised = False
    try:
        decrypt_chacha20_poly1305(key, nonce, bytes(corrupted_ct), aad)
    except InvalidTag:
        raised = True
    assert raised, "ChaCha20Poly1305 decrypt with corrupted ciphertext must raise InvalidTag"

    # Wrong nonce raises InvalidTag
    wrong_nonce = bytearray(nonce)
    wrong_nonce[0] ^= 0x01
    raised = False
    try:
        decrypt_chacha20_poly1305(key, bytes(wrong_nonce), ciphertext, aad)
    except InvalidTag:
        raised = True
    assert raised, "ChaCha20Poly1305 decrypt with wrong nonce must raise InvalidTag"


def main() -> None:
    test_invalid_tag_is_exception()
    test_aes_gcm_invalid_tag_on_corrupted_ciphertext()
    test_aes_gcm_invalid_tag_on_mismatched_aad()
    test_chacha20_poly1305_invalid_tag_on_tampering()
    print("All contract assertions passed.")


if __name__ == "__main__":
    main()

Origin Seeder

anonymous