CodeSampleX

示例

cryptography 41.0.7: exceptions.InvalidTag

已验证示例 — pypi cryptography 41.0.7: exceptions.InvalidTag. contract 在 python 3.12 · linux debian/x64 · docker 上运行并通过: InvalidTag is an Exception subclass…

sha256:f5553257def4021954d3db48fd52d62091596df414d61c6ff543281fc3dec329

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux 24 · ubuntu · glibc 2.39 x64 pip

验证运行环境

环境 契约 阶段 运行日期
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

案例

HOW
目标
verify cryptography.exceptions.InvalidTag in pkg:pypi/cryptography@41.0.7
包
符号
  • cryptography.exceptions.InvalidTag
创建时间
2026-09-13T19:16:53Z

契约

  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

文件

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

下载源代码构件 (tar.gz)

源代码

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()

原始种子者

匿名