CodeSampleX

Exemple

cipher 0.5.2

Échantillon vérifié pour cargo cipher 0.5.2. Le contrat s'est exécuté sur rust 1 · linux alpine/x64 · docker et a réussi : KeyInit::new and…

sha256:43a1f398176a49d73a2c30006397f865c2f11f76a57da2a52735af1897cb63a9

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux · alpine · musl x64 cargo

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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

Cas

HOW
Objectif
verify pkg:cargo/cipher@0.5.2
Paquets
Créé
2026-11-09T00:51:29Z

Contrat

  1. KeyInit::new and KeyInit::new_from_slice initialize block ciphers and reject invalid key lengths with InvalidLength
  2. BlockCipherEncrypt and BlockCipherDecrypt round-trip single and multiple blocks in-place and buffer-to-buffer
  3. TweakBlockCipherEncrypt, TweakBlockCipherDecrypt, and ZeroTweak apply tweak-dependent and zero-tweak block transformations
  4. StreamCipher and StreamCipherSeek apply keystreams, seek across byte positions, and return StreamCipherError when exceeding keystream bounds

Fichiers

  • Cargo.lock
  • Cargo.toml
  • PROMPT.md
  • csx.json
  • spec.json
  • src/lib.rs
  • test/contract.rs

Télécharger l’artefact source (tar.gz)

Code source

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

[[package]]
name = "cipher"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
dependencies = [
 "crypto-common",
 "inout",
]

[[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 = "inout"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9"
dependencies = [
 "hybrid-array",
]

[[package]]
name = "sample-cipher"
version = "1.0.0"
dependencies = [
 "cipher",
]

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

[dependencies]
cipher = "=0.5.2"

[[bin]]
name = "contract"
path = "test/contract.rs"
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/cipher@0.5.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/cipher@0.5.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:508fa3cf7cbb5f1c94bfedb3c354d6af40b4a92dc272c5bdda2e1daaef9d49b5","contract":["KeyInit::new and KeyInit::new_from_slice initialize block ciphers and reject invalid key lengths with InvalidLength","BlockCipherEncrypt and BlockCipherDecrypt round-trip single and multiple blocks in-place and buffer-to-buffer","TweakBlockCipherEncrypt, TweakBlockCipherDecrypt, and ZeroTweak apply tweak-dependent and zero-tweak block transformations","StreamCipher and StreamCipherSeek apply keystreams, seek across byte positions, and return StreamCipherError when exceeding keystream bounds"],"goal":"verify pkg:cargo/cipher@0.5.2","kind":"HOW","packages":["pkg:cargo/cipher@0.5.2"],"schemaVersion":1},"contractCommand":["cargo","run","--offline"],"environment":{"arch":"x64","distro":"alpine","ecosystem":"cargo","libc":"musl","os":"linux","packageManager":"cargo","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/cipher@0.5.2"],"schemaVersion":1,"subject":"pkg:cargo/cipher@0.5.2","verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:cargo/cipher@0.5.2",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/cipher@0.5.2"
  ]
}
src/lib.rs
//! Clean-room verification sample for cipher@0.5.2.

use cipher::{
    consts::{U1, U8, U16},
    Block, BlockCipherDecBackend, BlockCipherDecClosure, BlockCipherDecrypt, BlockCipherEncBackend,
    BlockCipherEncClosure, BlockCipherEncrypt, BlockSizeUser, InOut, InOutBuf, Iv, IvSizeUser, Key,
    KeyInit, KeyIvInit, KeySizeUser, OverflowError, ParBlocksSizeUser, SeekNum, StreamCipher,
    StreamCipherError, StreamCipherSeek, Tweak, TweakBlockCipherDecBackend,
    TweakBlockCipherDecClosure, TweakBlockCipherDecrypt, TweakBlockCipherEncBackend,
    TweakBlockCipherEncClosure, TweakBlockCipherEncrypt, TweakSizeUser,
};

#[derive(Clone, Debug)]
pub struct ToyBlockCipher {
    key: Block<Self>,
}

impl KeySizeUser for ToyBlockCipher {
    type KeySize = U16;
}

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

impl BlockSizeUser for ToyBlockCipher {
    type BlockSize = U16;
}

impl ParBlocksSizeUser for ToyBlockCipher {
    type ParBlocksSize = U1;
}

impl BlockCipherEncBackend for ToyBlockCipher {
    fn encrypt_block(&self, mut block: InOut<'_, '_, Block<Self>>) {
        let inp = *block.get_in();
        let out = block.get_out();
        for i in 0..16 {
            out[i] = inp[i].wrapping_add(self.key[i]) ^ (i as u8);
        }
    }
}

impl BlockCipherDecBackend for ToyBlockCipher {
    fn decrypt_block(&self, mut block: InOut<'_, '_, Block<Self>>) {
        let inp = *block.get_in();
        let out = block.get_out();
        for i in 0..16 {
            out[i] = (inp[i] ^ (i as u8)).wrapping_sub(self.key[i]);
        }
    }
}

impl BlockCipherEncrypt for ToyBlockCipher {
    fn encrypt_with_backend(&self, f: impl BlockCipherEncClosure<BlockSize = Self::BlockSize>) {
        f.call(self);
    }
}

impl BlockCipherDecrypt for ToyBlockCipher {
    fn decrypt_with_backend(&self, f: impl BlockCipherDecClosure<BlockSize = Self::BlockSize>) {
        f.call(self);
    }
}

#[derive(Clone, Debug)]
pub struct ToyTweakCipher {
    key: [u8; 8],
}

impl KeySizeUser for ToyTweakCipher {
    type KeySize = U8;
}

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

impl BlockSizeUser for ToyTweakCipher {
    type BlockSize = U8;
}

impl TweakSizeUser for ToyTweakCipher {
    type TweakSize = U8;
}

impl TweakBlockCipherEncBackend for ToyTweakCipher {
    fn encrypt_block_inout(&self, tweak: &Tweak<Self>, mut block: InOut<'_, '_, Block<Self>>) {
        let inp = *block.get_in();
        let out = block.get_out();
        for i in 0..8 {
            out[i] = (inp[i] ^ self.key[i]).wrapping_add(tweak[i]);
        }
    }
}

impl TweakBlockCipherDecBackend for ToyTweakCipher {
    fn decrypt_block_inout(&self, tweak: &Tweak<Self>, mut block: InOut<'_, '_, Block<Self>>) {
        let inp = *block.get_in();
        let out = block.get_out();
        for i in 0..8 {
            out[i] = inp[i].wrapping_sub(tweak[i]) ^ self.key[i];
        }
    }
}

impl TweakBlockCipherEncrypt for ToyTweakCipher {
    fn encrypt_with_backend(
        &self,
        f: impl TweakBlockCipherEncClosure<BlockSize = Self::BlockSize, TweakSize = Self::TweakSize>,
    ) {
        f.call(self);
    }
}

impl TweakBlockCipherDecrypt for ToyTweakCipher {
    fn decrypt_with_backend(
        &self,
        f: impl TweakBlockCipherDecClosure<BlockSize = Self::BlockSize, TweakSize = Self::TweakSize>,
    ) {
        f.call(self);
    }
}

#[derive(Clone, Debug)]
pub struct ToyStreamCipher {
    key: [u8; 16],
    iv: [u8; 8],
    pos: usize,
    limit: usize,
}

impl KeySizeUser for ToyStreamCipher {
    type KeySize = U16;
}

impl IvSizeUser for ToyStreamCipher {
    type IvSize = U8;
}

impl KeyIvInit for ToyStreamCipher {
    fn new(key: &Key<Self>, iv: &Iv<Self>) -> Self {
        Self {
            key: (*key).into(),
            iv: (*iv).into(),
            pos: 0,
            limit: 64,
        }
    }
}

impl ToyStreamCipher {
    fn keystream_byte(&self, offset: usize) -> u8 {
        let k = self.key[offset % 16];
        let v = self.iv[offset % 8];
        k.wrapping_add(v) ^ (offset as u8)
    }
}

impl StreamCipher for ToyStreamCipher {
    fn check_remaining(&self, data_len: usize) -> Result<(), StreamCipherError> {
        let end = self.pos.checked_add(data_len).ok_or(StreamCipherError)?;
        if end > self.limit {
            Err(StreamCipherError)
        } else {
            Ok(())
        }
    }

    fn unchecked_apply_keystream_inout(&mut self, mut buf: InOutBuf<'_, '_, u8>) {
        let len = buf.len();
        for i in 0..len {
            let ks = self.keystream_byte(self.pos + i);
            let mut item = buf.get(i);
            let b = *item.get_in();
            *item.get_out() = b ^ ks;
        }
        self.pos += len;
    }

    fn unchecked_write_keystream(&mut self, buf: &mut [u8]) {
        for (i, byte) in buf.iter_mut().enumerate() {
            *byte = self.keystream_byte(self.pos + i);
        }
        self.pos += buf.len();
    }
}

impl StreamCipherSeek for ToyStreamCipher {
    fn try_current_pos<T: SeekNum>(&self) -> Result<T, OverflowError> {
        let (block, byte) = self.pos.into_block_byte::<u32>(1)?;
        if byte == 0 {
            T::from_block_byte(block, 1, 1).map_err(|_| OverflowError)
        } else {
            Err(OverflowError)
        }
    }

    fn try_seek<T: SeekNum>(&mut self, pos: T) -> Result<(), StreamCipherError> {
        let (block, _byte) = pos
            .into_block_byte::<u32>(1)
            .map_err(|_| StreamCipherError)?;
        let new_pos = block as usize;
        if new_pos > self.limit {
            return Err(StreamCipherError);
        }
        self.pos = new_pos;
        Ok(())
    }
}
test/contract.rs
use cipher::{
    array::Array, BlockCipherDecrypt, BlockCipherEncrypt, InvalidLength, KeyInit, KeyIvInit,
    StreamCipher, StreamCipherError, StreamCipherSeek, TweakBlockCipherDecrypt,
    TweakBlockCipherEncrypt, ZeroTweak,
};
use sample_cipher::{ToyBlockCipher, ToyStreamCipher, ToyTweakCipher};

fn main() {
    // 1. KeyInit::new and KeyInit::new_from_slice initialize block ciphers and reject invalid key lengths
    let key_bytes = [
        0x01u8, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
        0x10,
    ];
    let cipher = ToyBlockCipher::new(&Array::from(key_bytes));
    let from_slice = ToyBlockCipher::new_from_slice(&key_bytes).expect("valid 16-byte key");
    assert_eq!(
        ToyBlockCipher::new_from_slice(&[0u8; 15]).unwrap_err(),
        InvalidLength
    );

    // 2. BlockCipherEncrypt and BlockCipherDecrypt round-trip single and multiple blocks in-place and buffer-to-buffer
    let plaintext = Array::from(*b"0123456789abcdef");
    let mut block = plaintext;
    cipher.encrypt_block(&mut block);
    assert_ne!(block, plaintext);
    from_slice.decrypt_block(&mut block);
    assert_eq!(block, plaintext);

    let mut out_block = Array::default();
    cipher.encrypt_block_b2b(&plaintext, &mut out_block);
    let mut recovered = Array::default();
    cipher.decrypt_block_b2b(&out_block, &mut recovered);
    assert_eq!(recovered, plaintext);

    let mut blocks = [
        Array::from(*b"block-number-one"),
        Array::from(*b"block-number-two"),
    ];
    let orig_blocks = blocks;
    cipher.encrypt_blocks(&mut blocks);
    assert_ne!(blocks, orig_blocks);
    cipher.decrypt_blocks(&mut blocks);
    assert_eq!(blocks, orig_blocks);

    // 3. TweakBlockCipherEncrypt, TweakBlockCipherDecrypt, and ZeroTweak apply tweak-dependent and zero-tweak transformations
    let tweak_cipher = ToyTweakCipher::new(&Array::from(*b"tweakkey"));
    let tweak_a = Array::from([1u8; 8]);
    let tweak_b = Array::from([2u8; 8]);
    let plain8 = Array::from(*b"ABCDEFGH");
    let mut enc_a = Array::default();
    let mut enc_b = Array::default();
    tweak_cipher.encrypt_block_b2b(&tweak_a, &plain8, &mut enc_a);
    tweak_cipher.encrypt_block_b2b(&tweak_b, &plain8, &mut enc_b);
    assert_ne!(enc_a, enc_b);

    let mut dec_a = enc_a;
    tweak_cipher.decrypt_block(&tweak_a, &mut dec_a);
    assert_eq!(dec_a, plain8);

    let zero_wrapped = ZeroTweak(tweak_cipher.clone());
    let mut zero_block = plain8;
    zero_wrapped.encrypt_block(&mut zero_block);
    let mut explicit_zero = plain8;
    tweak_cipher.encrypt_block(&Array::default(), &mut explicit_zero);
    assert_eq!(zero_block, explicit_zero);
    zero_wrapped.decrypt_block(&mut zero_block);
    assert_eq!(zero_block, plain8);

    // 4. StreamCipher and StreamCipherSeek apply keystreams, seek across positions, and enforce keystream bounds
    let iv = Array::from(*b"uniqueiv");
    let mut stream = ToyStreamCipher::new(&Array::from(key_bytes), &iv);
    let msg = b"stream cipher verification message";
    let mut buf = *msg;
    stream.apply_keystream(&mut buf);
    assert_ne!(&buf, msg);
    assert_eq!(stream.current_pos::<usize>(), msg.len());

    stream.seek(0usize);
    assert_eq!(stream.current_pos::<usize>(), 0);
    stream.apply_keystream(&mut buf);
    assert_eq!(&buf, msg);

    stream.seek(60usize);
    let mut too_long = [0u8; 8];
    assert!(matches!(
        stream.try_apply_keystream(&mut too_long),
        Err(StreamCipherError)
    ));
    assert!(matches!(stream.try_seek(65usize), Err(StreamCipherError)));
}

Seeder d'origine

anonyme