CodeSampleX

Beispiel

crypto-common 0.2.2: BlockSizeUser, KeyExport, KeyInit

Verifiziertes Beispiel für cargo crypto-common 0.2.2: BlockSizeUser, KeyExport, KeyInit. Der Vertrag lief auf rust 1 · linux alpine/x64 · docker und bestand.

sha256:c4af1e667fbb6570d3d46badde6336f2509af61fd788e71735ec4e22641429ca

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
1
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung linux x64 cargo

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
rust 1 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1rust:1-alpine@sha256:a10e64dd139b…
2026-11-09

Fall

HOW
Ziel
verify pkg:cargo/crypto-common@0.2.2
Pakete
Symbole
  • BlockSizeUser
  • KeyExport
  • KeyInit
  • KeyIvInit
  • OutputSizeUser
  • SerializableState
  • SetIvState
  • TryKeyInit
Erstellt
2026-11-09T05:48:52Z

Contract

  1. BlockSizeUser::block_size(), OutputSizeUser::output_size(), and KeySizeUser::key_size() return the typenum USIZE constants matching Block<T>, Output<T>, and Key<T> hybrid_array lengths
  2. KeyInit::new_from_slice returns Ok(Self) for slices matching KeySize and Err(InvalidLength) otherwise, while KeyExport::to_bytes round-trips the key bytes
  3. Blanket KeyIvInit over InnerIvInit + KeyInit initializes stream cipher types via new_from_slices and SetIvState::peek restores the original IvState after running its closure
  4. TryKeyInit::new_from_slice returns Err(InvalidKey) when slice length mismatches or when TryKeyInit::new rejects weak key bytes
  5. hazmat::SerializableState serializes and deserializes state arrays for both primitive integers (u32 little-endian) and custom types returning Err(DeserializeStateError) on invalid state

Dateien

  • Cargo.lock
  • Cargo.toml
  • PROMPT.md
  • csx.json
  • spec.json
  • src/main.rs

Quellartefakt herunterladen (tar.gz)

Quelltext

Cargo.lock
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4

[[package]]
name = "crypto-common"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
 "hybrid-array",
]

[[package]]
name = "hybrid-array"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
dependencies = [
 "typenum",
]

[[package]]
name = "sample-crypto-common"
version = "0.1.0"
dependencies = [
 "crypto-common",
]

[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
Cargo.toml
[package]
name = "sample-crypto-common"
version = "0.1.0"
edition = "2021"

[dependencies]
crypto-common = "=0.2.2"
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 pkg:cargo/crypto-common@0.2.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/crypto-common@0.2.2

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:f5ee27cffb3ec91d082103ad0f05d695c28617beb1080dceccdbea4376034dbe","contract":["BlockSizeUser::block_size(), OutputSizeUser::output_size(), and KeySizeUser::key_size() return the typenum USIZE constants matching Block\u003cT\u003e, Output\u003cT\u003e, and Key\u003cT\u003e hybrid_array lengths","KeyInit::new_from_slice returns Ok(Self) for slices matching KeySize and Err(InvalidLength) otherwise, while KeyExport::to_bytes round-trips the key bytes","Blanket KeyIvInit over InnerIvInit + KeyInit initializes stream cipher types via new_from_slices and SetIvState::peek restores the original IvState after running its closure","TryKeyInit::new_from_slice returns Err(InvalidKey) when slice length mismatches or when TryKeyInit::new rejects weak key bytes","hazmat::SerializableState serializes and deserializes state arrays for both primitive integers (u32 little-endian) and custom types returning Err(DeserializeStateError) on invalid state"],"goal":"verify pkg:cargo/crypto-common@0.2.2","kind":"HOW","packages":["pkg:cargo/crypto-common@0.2.2"],"schemaVersion":1,"symbols":["BlockSizeUser","KeyExport","KeyInit","KeyIvInit","OutputSizeUser","SerializableState","SetIvState","TryKeyInit"]},"contractCommand":["cargo","run","--offline"],"environment":{"arch":"x64","ecosystem":"cargo","os":"linux","packageManager":"cargo","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/crypto-common@0.2.2"],"schemaVersion":1,"subject":"pkg:cargo/crypto-common@0.2.2","symbols":["BlockSizeUser","KeyExport","KeyInit","KeyIvInit","OutputSizeUser","SerializableState","SetIvState","TryKeyInit"],"verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:cargo/crypto-common@0.2.2",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/crypto-common@0.2.2"
  ]
}
src/main.rs
use crypto_common::{
    Block, BlockSizeUser, InnerIvInit, InnerUser, InvalidKey, InvalidLength, Iv, IvSizeUser,
    IvState, Key, KeyExport, KeyInit, KeyIvInit, KeySizeUser, Output, OutputSizeUser, Reset,
    SetIvState, TryKeyInit,
    array::Array,
    hazmat::{DeserializeStateError, SerializableState, SerializedState},
    typenum::{U8, U12, U16, U17, U32},
};

#[derive(Clone, Debug, PartialEq, Eq)]
struct DemoBlockCipher {
    key: [u8; 16],
}

impl BlockSizeUser for DemoBlockCipher {
    type BlockSize = U16;
}

impl OutputSizeUser for DemoBlockCipher {
    type OutputSize = U32;
}

impl KeySizeUser for DemoBlockCipher {
    type KeySize = U16;
}

impl KeyInit for DemoBlockCipher {
    fn new(key: &Key<Self>) -> Self {
        Self { key: (*key).into() }
    }
}

impl KeyExport for DemoBlockCipher {
    fn to_bytes(&self) -> Key<Self> {
        self.key.into()
    }
}

impl Reset for DemoBlockCipher {
    fn reset(&mut self) {
        self.key = [0u8; 16];
    }
}

impl SerializableState for DemoBlockCipher {
    type SerializedStateSize = U17;

    fn serialize(&self) -> SerializedState<Self> {
        let mut out = Array::<u8, U17>::default();
        out[0] = 1; // version tag
        out[1..17].copy_from_slice(&self.key);
        out
    }

    fn deserialize(serialized_state: &SerializedState<Self>) -> Result<Self, DeserializeStateError> {
        if serialized_state[0] != 1 {
            return Err(DeserializeStateError);
        }
        let mut key = [0u8; 16];
        key.copy_from_slice(&serialized_state[1..17]);
        Ok(Self { key })
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct DemoStreamCipher {
    inner: DemoBlockCipher,
    iv: [u8; 12],
}

impl InnerUser for DemoStreamCipher {
    type Inner = DemoBlockCipher;
}

impl IvSizeUser for DemoStreamCipher {
    type IvSize = U12;
}

impl InnerIvInit for DemoStreamCipher {
    fn inner_iv_init(inner: Self::Inner, iv: &Iv<Self>) -> Self {
        Self {
            inner,
            iv: (*iv).into(),
        }
    }
}

impl IvState for DemoStreamCipher {
    fn iv_state(&self) -> Iv<Self> {
        self.iv.into()
    }
}

impl SetIvState for DemoStreamCipher {
    fn set_iv(&mut self, iv: &Iv<Self>) {
        self.iv = (*iv).into();
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct NonZeroKeyCipher([u8; 8]);

impl KeySizeUser for NonZeroKeyCipher {
    type KeySize = U8;
}

impl TryKeyInit for NonZeroKeyCipher {
    fn new(key: &Key<Self>) -> Result<Self, InvalidKey> {
        let bytes: [u8; 8] = (*key).into();
        if bytes.iter().all(|&b| b == 0) {
            return Err(InvalidKey);
        }
        Ok(Self(bytes))
    }
}

fn main() {
    // 1. BlockSizeUser, OutputSizeUser, KeySizeUser size constants & Array aliases
    assert_eq!(DemoBlockCipher::block_size(), 16);
    assert_eq!(DemoBlockCipher::output_size(), 32);
    assert_eq!(DemoBlockCipher::key_size(), 16);
    assert_eq!(Block::<DemoBlockCipher>::default().len(), 16);
    assert_eq!(Output::<DemoBlockCipher>::default().len(), 32);

    // 2. KeyInit::new_from_slice and KeyExport::to_bytes, plus Reset
    let raw_key = [0xABu8; 16];
    let mut cipher = DemoBlockCipher::new_from_slice(&raw_key).expect("16-byte key is valid");
    assert_eq!(cipher.to_bytes().as_slice(), &raw_key);
    assert_eq!(
        DemoBlockCipher::new_from_slice(&[0xABu8; 15]),
        Err(InvalidLength)
    );

    // 3. SerializableState on custom type and primitive u32
    let state = cipher.serialize();
    assert_eq!(state.len(), 17);
    let restored = DemoBlockCipher::deserialize(&state).expect("valid state");
    assert_eq!(restored, cipher);

    let mut bad_state = state;
    bad_state[0] = 99;
    assert_eq!(
        DemoBlockCipher::deserialize(&bad_state),
        Err(DeserializeStateError)
    );

    let word: u32 = 0x1234_5678;
    let word_state = word.serialize();
    assert_eq!(word_state.as_slice(), &[0x78, 0x56, 0x34, 0x12]);
    assert_eq!(u32::deserialize(&word_state), Ok(word));

    cipher.reset();
    assert_eq!(cipher.to_bytes().as_slice(), &[0u8; 16]);

    // 4. Blanket KeyIvInit via InnerIvInit + IvState + SetIvState::peek
    assert_eq!(DemoStreamCipher::key_size(), 16);
    assert_eq!(DemoStreamCipher::iv_size(), 12);
    let iv_bytes = [0x11u8; 12];
    let mut stream =
        DemoStreamCipher::new_from_slices(&raw_key, &iv_bytes).expect("valid key and iv");
    assert_eq!(stream.iv_state().as_slice(), &iv_bytes);
    assert_eq!(
        DemoStreamCipher::new_from_slices(&raw_key, &[0x11u8; 11]),
        Err(InvalidLength)
    );

    let peeked_iv = stream.peek(|s| {
        let temp_iv: Iv<DemoStreamCipher> = [0xFFu8; 12].into();
        s.set_iv(&temp_iv);
        s.iv_state()
    });
    assert_eq!(peeked_iv.as_slice(), &[0xFFu8; 12]);
    assert_eq!(stream.iv_state().as_slice(), &iv_bytes);

    // 5. TryKeyInit with InvalidKey on wrong slice length or rejected weak key
    assert_eq!(NonZeroKeyCipher::new_from_slice(&[0u8; 8]), Err(InvalidKey));
    assert_eq!(NonZeroKeyCipher::new_from_slice(&[1u8; 7]), Err(InvalidKey));
    let valid_try = NonZeroKeyCipher::new_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8])
        .expect("non-zero 8-byte key is accepted");
    assert_eq!(valid_try.0, [1, 2, 3, 4, 5, 6, 7, 8]);
}

Ursprungs-Seeder

anonym