CodeSampleX

Sample

cryptography 41.0.7: algorithms.AES

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

sha256:d21171dfc17d4c7909afaf60932e465b17d4da4af1c78ffad17fcf7961e035ad

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 algorithms.AES in pkg:pypi/cryptography@41.0.7
Packages
Symbols
  • algorithms.AES
Created
2026-09-13T18:53:07Z

Contract

  1. assert algorithms.AES supports 128, 192, and 256-bit keys and exposes name and block_size attributes
  2. assert algorithms.AES raises ValueError when initialized with invalid key length
  3. assert Cipher with algorithms.AES and modes.CBC encrypts and decrypts padded plaintext
  4. assert Cipher with algorithms.AES and modes.GCM authenticates and decrypts payload and raises InvalidTag on tampering

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 algorithms.AES 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:
  - algorithms.AES

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:117885ff2def362d0b1fd67ba878cffcf4129aafd8f3d0255af57544db98c79b","contract":["assert algorithms.AES supports 128, 192, and 256-bit keys and exposes name and block_size attributes","assert algorithms.AES raises ValueError when initialized with invalid key length","assert Cipher with algorithms.AES and modes.CBC encrypts and decrypts padded plaintext","assert Cipher with algorithms.AES and modes.GCM authenticates and decrypts payload and raises InvalidTag on tampering"],"goal":"verify algorithms.AES in pkg:pypi/cryptography@41.0.7","kind":"HOW","packages":["pkg:pypi/cryptography@41.0.7"],"schemaVersion":1,"symbols":["algorithms.AES"]},"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":["algorithms.AES"],"verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "verify-cryptography-aes"
version = "0.1.0"
dependencies = [
    "cryptography==41.0.7",
]
requirements.txt
cryptography==41.0.7
sample.py
"""Demonstration of AES symmetric encryption using cryptography algorithms.AES."""

from typing import Tuple
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding


def create_aes_algorithm(key: bytes) -> algorithms.AES:
    """Create an AES algorithm instance with the specified key."""
    return algorithms.AES(key)


def aes_cbc_encrypt(key: bytes, iv: bytes, plaintext: bytes) -> bytes:
    """Encrypt plaintext using AES in CBC mode with PKCS7 padding."""
    padder = padding.PKCS7(algorithms.AES.block_size).padder()
    padded_data = padder.update(plaintext) + padder.finalize()
    cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
    encryptor = cipher.encryptor()
    return encryptor.update(padded_data) + encryptor.finalize()


def aes_cbc_decrypt(key: bytes, iv: bytes, ciphertext: bytes) -> bytes:
    """Decrypt ciphertext using AES in CBC mode with PKCS7 unpadding."""
    cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
    decryptor = cipher.decryptor()
    padded_data = decryptor.update(ciphertext) + decryptor.finalize()
    unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
    return unpadder.update(padded_data) + unpadder.finalize()


def aes_gcm_encrypt(
    key: bytes, nonce: bytes, plaintext: bytes, associated_data: bytes = b""
) -> Tuple[bytes, bytes]:
    """Encrypt plaintext using AES in GCM mode, returning ciphertext and tag."""
    cipher = Cipher(algorithms.AES(key), modes.GCM(nonce))
    encryptor = cipher.encryptor()
    if associated_data:
        encryptor.authenticate_additional_data(associated_data)
    ciphertext = encryptor.update(plaintext) + encryptor.finalize()
    return ciphertext, encryptor.tag


def aes_gcm_decrypt(
    key: bytes,
    nonce: bytes,
    ciphertext: bytes,
    tag: bytes,
    associated_data: bytes = b"",
) -> bytes:
    """Decrypt ciphertext using AES in GCM mode and verify authenticity."""
    cipher = Cipher(algorithms.AES(key), modes.GCM(nonce, tag))
    decryptor = cipher.decryptor()
    if associated_data:
        decryptor.authenticate_additional_data(associated_data)
    return decryptor.update(ciphertext) + decryptor.finalize()
spec.json
{
  "schemaVersion": 1,
  "goal": "verify algorithms.AES in pkg:pypi/cryptography@41.0.7",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/cryptography@41.0.7"
  ],
  "symbols": [
    "algorithms.AES"
  ]
}
test/contract.py
"""Contract verification test for algorithms.AES in cryptography."""

import os
import sys

# Ensure sample module can be imported from root
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives.ciphers import algorithms, modes
from sample import (
    create_aes_algorithm,
    aes_cbc_encrypt,
    aes_cbc_decrypt,
    aes_gcm_encrypt,
    aes_gcm_decrypt,
)


def test_aes_key_sizes_and_attributes() -> None:
    """Assertion 1: assert algorithms.AES supports 128, 192, and 256-bit keys and exposes name and block_size attributes."""
    expected_key_sizes = [(16, 128), (24, 192), (32, 256)]
    for byte_len, bit_len in expected_key_sizes:
        key = b"\x01" * byte_len
        algo = create_aes_algorithm(key)
        assert algo.name == "AES"
        assert algo.key_size == bit_len
        assert algo.block_size == 128
        assert algo.key == key

    # Class-level attributes
    assert algorithms.AES.name == "AES"
    assert algorithms.AES.block_size == 128
    assert algorithms.AES.key_sizes == frozenset([128, 192, 256, 512])


def test_aes_invalid_key_length_raises_value_error() -> None:
    """Assertion 2: assert algorithms.AES raises ValueError when initialized with invalid key length."""
    invalid_lengths = [0, 8, 15, 20, 31, 33, 65]
    for length in invalid_lengths:
        invalid_key = b"\xaa" * length
        raised = False
        try:
            algorithms.AES(invalid_key)
        except ValueError:
            raised = True
        assert raised, f"Expected ValueError for AES key of length {length}"


def test_aes_cbc_encrypt_decrypt() -> None:
    """Assertion 3: assert Cipher with algorithms.AES and modes.CBC encrypts and decrypts padded plaintext."""
    key = b"K" * 32  # 256-bit AES key
    iv = b"I" * 16   # 128-bit initialization vector
    plaintext = b"AES CBC mode verification payload with PKCS7 padding test."

    ciphertext = aes_cbc_encrypt(key, iv, plaintext)
    assert ciphertext != plaintext
    assert len(ciphertext) % 16 == 0

    decrypted = aes_cbc_decrypt(key, iv, ciphertext)
    assert decrypted == plaintext


def test_aes_gcm_authenticated_encryption_and_tamper_detection() -> None:
    """Assertion 4: assert Cipher with algorithms.AES and modes.GCM authenticates and decrypts payload and raises InvalidTag on tampering."""
    key = b"G" * 32
    nonce = b"N" * 12
    aad = b"authenticated_header_data"
    plaintext = b"Confidential and authenticated message"

    ciphertext, tag = aes_gcm_encrypt(key, nonce, plaintext, associated_data=aad)
    assert len(tag) == 16
    assert ciphertext != plaintext

    decrypted = aes_gcm_decrypt(key, nonce, ciphertext, tag, associated_data=aad)
    assert decrypted == plaintext

    # Tampered ciphertext
    tampered_ciphertext = bytes([ciphertext[0] ^ 0x01]) + ciphertext[1:]
    tamper_detected = False
    try:
        aes_gcm_decrypt(key, nonce, tampered_ciphertext, tag, associated_data=aad)
    except InvalidTag:
        tamper_detected = True
    assert tamper_detected, "GCM decryption should fail with InvalidTag on tampered ciphertext"

    # Tampered tag
    tampered_tag = bytes([tag[0] ^ 0x01]) + tag[1:]
    tag_tamper_detected = False
    try:
        aes_gcm_decrypt(key, nonce, ciphertext, tampered_tag, associated_data=aad)
    except InvalidTag:
        tag_tamper_detected = True
    assert tag_tamper_detected, "GCM decryption should fail with InvalidTag on tampered tag"

    # Tampered AAD
    aad_tamper_detected = False
    try:
        aes_gcm_decrypt(key, nonce, ciphertext, tag, associated_data=b"wrong_header")
    except InvalidTag:
        aad_tamper_detected = True
    assert aad_tamper_detected, "GCM decryption should fail with InvalidTag on tampered AAD"


def main() -> None:
    test_aes_key_sizes_and_attributes()
    test_aes_invalid_key_length_raises_value_error()
    test_aes_cbc_encrypt_decrypt()
    test_aes_gcm_authenticated_encryption_and_tamper_detection()
    print("All contract assertions passed.")


if __name__ == "__main__":
    main()

Origin Seeder

anonymous