CodeSampleX

示例

crypto-common 0.2.2

已验证示例 — cargo crypto-common 0.2.2. contract 在 rust 1 · linux alpine/x64 · docker 上运行并通过: BlockSizeUser::block_size(), OutputSizeUser::output_size(), and…

sha256:328104af56c03255cc4485df572b431dce645be4937d7a00c0d1de02a83eae72

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

执行证据

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

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux x64 cargo

验证运行环境

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

案例

HOW
目标
verify pkg:cargo/crypto-common@0.2.2
包
创建时间
2026-11-09T07:27:42Z

契约

  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

文件

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

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

源代码

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:a9e30dcd1b0c68d4acd561dc24678a3dbb4e141093383de3ca3346b33ce37055","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},"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","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 FixedKeyBlockAlgo {
    key_bytes: [u8; 16],
}

impl BlockSizeUser for FixedKeyBlockAlgo {
    type BlockSize = U16;
}

impl OutputSizeUser for FixedKeyBlockAlgo {
    type OutputSize = U32;
}

impl KeySizeUser for FixedKeyBlockAlgo {
    type KeySize = U16;
}

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

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

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

impl SerializableState for FixedKeyBlockAlgo {
    type SerializedStateSize = U17;

    fn serialize(&self) -> SerializedState<Self> {
        let mut buf = Array::<u8, U17>::default();
        buf[0] = 0x42;
        buf[1..17].copy_from_slice(&self.key_bytes);
        buf
    }

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

#[derive(Clone, Debug, PartialEq, Eq)]
struct StreamWrapper {
    core: FixedKeyBlockAlgo,
    nonce: [u8; 12],
}

impl InnerUser for StreamWrapper {
    type Inner = FixedKeyBlockAlgo;
}

impl IvSizeUser for StreamWrapper {
    type IvSize = U12;
}

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

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

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

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

impl KeySizeUser for CheckedKeyAlgo {
    type KeySize = U8;
}

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

fn main() {
    assert_eq!(FixedKeyBlockAlgo::block_size(), 16);
    assert_eq!(FixedKeyBlockAlgo::output_size(), 32);
    assert_eq!(FixedKeyBlockAlgo::key_size(), 16);
    assert_eq!(Block::<FixedKeyBlockAlgo>::default().len(), 16);
    assert_eq!(Output::<FixedKeyBlockAlgo>::default().len(), 32);

    let key_input = [0x5Au8; 16];
    let mut algo = FixedKeyBlockAlgo::new_from_slice(&key_input).expect("valid 16-byte key");
    assert_eq!(algo.to_bytes().as_slice(), &key_input);
    assert_eq!(
        FixedKeyBlockAlgo::new_from_slice(&[0x5Au8; 15]),
        Err(InvalidLength)
    );

    let serialized = algo.serialize();
    assert_eq!(serialized.len(), 17);
    let deserialized = FixedKeyBlockAlgo::deserialize(&serialized).expect("valid state header");
    assert_eq!(deserialized, algo);

    let mut invalid_state = serialized;
    invalid_state[0] = 0x00;
    assert_eq!(
        FixedKeyBlockAlgo::deserialize(&invalid_state),
        Err(DeserializeStateError)
    );

    let val: u32 = 0xCAFE_BABE;
    let val_bytes = val.serialize();
    assert_eq!(val_bytes.as_slice(), &[0xBE, 0xBA, 0xFE, 0xCA]);
    assert_eq!(u32::deserialize(&val_bytes), Ok(val));

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

    assert_eq!(StreamWrapper::key_size(), 16);
    assert_eq!(StreamWrapper::iv_size(), 12);
    let nonce_input = [0x22u8; 12];
    let mut stream =
        StreamWrapper::new_from_slices(&key_input, &nonce_input).expect("valid key and nonce");
    assert_eq!(stream.iv_state().as_slice(), &nonce_input);
    assert_eq!(
        StreamWrapper::new_from_slices(&key_input, &[0x22u8; 11]),
        Err(InvalidLength)
    );

    let inside_iv = stream.peek(|st| {
        let override_iv: Iv<StreamWrapper> = [0x99u8; 12].into();
        st.set_iv(&override_iv);
        st.iv_state()
    });
    assert_eq!(inside_iv.as_slice(), &[0x99u8; 12]);
    assert_eq!(stream.iv_state().as_slice(), &nonce_input);

    assert_eq!(CheckedKeyAlgo::new_from_slice(&[0u8; 8]), Err(InvalidKey));
    assert_eq!(CheckedKeyAlgo::new_from_slice(&[1u8; 7]), Err(InvalidKey));
    let checked =
        CheckedKeyAlgo::new_from_slice(&[10, 20, 30, 40, 50, 60, 70, 80]).expect("valid non-zero key");
    assert_eq!(checked.0, [10, 20, 30, 40, 50, 60, 70, 80]);
}

原始种子者

匿名