CodeSampleX

Beispiel

hmac 0.12.1: HmacCore, Mac, SimpleHmac

Verifiziertes Beispiel für cargo hmac 0.12.1: HmacCore, Mac, SimpleHmac. Der Vertrag lief auf rust 1 · linux alpine/x64 · docker und bestand.

sha256:114f7c455784a1f8aa4aa47f6b54d71a909fc0adb3fd75b43681b5b01bf9af55

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:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1rust:1-alpine@sha256:a10e64dd139b…
2026-11-04

Fall

HOW
Ziel
verify pkg:cargo/hmac@0.12.1
Pakete
Symbole
  • Hmac
  • HmacCore
  • Mac
  • SimpleHmac
Erstellt
2026-11-04T01:10:22Z

Contract

  1. Hmac::new_from_slice accepts keys of any byte length including keys shorter and longer than the underlying digest block size
  2. Mac::update and Mac::chain_update (consuming self and returning Self) feed message bytes and produce identical 32-byte authentication tags via Mac::finalize
  3. Mac::verify_slice succeeds for an authentic tag and returns an error when any tag byte is modified
  4. Mac::verify_truncated_left and Mac::verify_truncated_right validate prefix and suffix tag slices in constant time
  5. Cloning an initialized Hmac instance reuses the precomputed key state across multiple messages without re-keying
  6. SimpleHmac and CoreWrapper<HmacCore<D>> produce the exact same authentication tag as Hmac<D> for identical keys and messages

Dateien

  • Cargo.lock
  • Cargo.toml
  • PROMPT.md
  • csx.json
  • spec.json
  • src/lib.rs
  • test/contract.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 = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
 "generic-array",
]

[[package]]
name = "crypto-common"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
 "generic-array",
 "typenum",
]

[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
 "block-buffer",
 "crypto-common",
 "subtle",
]

[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
 "typenum",
 "version_check",
]

[[package]]
name = "hmac"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
 "digest",
]

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

[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"

[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"

[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
Cargo.toml
[package]
name = "sample-hmac"
version = "0.1.0"
edition = "2021"

[[bin]]
name = "sample-hmac"
path = "test/contract.rs"

[dependencies]
hmac = "=0.12.1"
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/hmac@0.12.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/hmac@0.12.1

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:0c8f228c8138c36c4beb64abca85009f6fb7e13da76f37ad10e02ebe6f6fdb2c","contract":["Hmac::new_from_slice accepts keys of any byte length including keys shorter and longer than the underlying digest block size","Mac::update and Mac::chain_update (consuming self and returning Self) feed message bytes and produce identical 32-byte authentication tags via Mac::finalize","Mac::verify_slice succeeds for an authentic tag and returns an error when any tag byte is modified","Mac::verify_truncated_left and Mac::verify_truncated_right validate prefix and suffix tag slices in constant time","Cloning an initialized Hmac instance reuses the precomputed key state across multiple messages without re-keying","SimpleHmac and CoreWrapper\u003cHmacCore\u003cD\u003e\u003e produce the exact same authentication tag as Hmac\u003cD\u003e for identical keys and messages"],"goal":"verify pkg:cargo/hmac@0.12.1","kind":"HOW","packages":["pkg:cargo/hmac@0.12.1"],"schemaVersion":1,"symbols":["Hmac","HmacCore","Mac","SimpleHmac"]},"contractCommand":["cargo","run","--offline"],"environment":{"arch":"x64","ecosystem":"cargo","os":"linux","packageManager":"cargo","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/hmac@0.12.1"],"schemaVersion":1,"subject":"pkg:cargo/hmac@0.12.1","symbols":["Hmac","HmacCore","Mac","SimpleHmac"],"verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:cargo/hmac@0.12.1",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/hmac@0.12.1"
  ]
}
src/lib.rs
use hmac::digest::{
    block_buffer::Eager,
    consts::{U32, U64},
    core_api::{
        AlgorithmName, Block, BlockSizeUser, Buffer, BufferKindUser, CoreWrapper, FixedOutputCore,
        OutputSizeUser, Reset, UpdateCore,
    },
    HashMarker, Output,
};
use hmac::{Hmac, HmacCore, Mac, SimpleHmac};
use std::fmt;

#[derive(Clone, Default)]
pub struct DeterministicHashCore {
    state: [u8; 32],
    total_len: u64,
}

impl HashMarker for DeterministicHashCore {}

impl BlockSizeUser for DeterministicHashCore {
    type BlockSize = U64;
}

impl BufferKindUser for DeterministicHashCore {
    type BufferKind = Eager;
}

impl OutputSizeUser for DeterministicHashCore {
    type OutputSize = U32;
}

impl UpdateCore for DeterministicHashCore {
    fn update_blocks(&mut self, blocks: &[Block<Self>]) {
        for block in blocks {
            for (i, &b) in block.iter().enumerate() {
                let idx = i % 32;
                let prev = self.state[(idx + 31) % 32];
                self.state[idx] = self.state[idx]
                    .wrapping_add(b ^ prev)
                    .rotate_left(((i % 7) + 1) as u32)
                    .wrapping_add(i as u8);
            }
            self.total_len = self.total_len.wrapping_add(64);
        }
    }
}

impl FixedOutputCore for DeterministicHashCore {
    fn finalize_fixed_core(&mut self, buffer: &mut Buffer<Self>, out: &mut Output<Self>) {
        let pos = buffer.get_pos();
        self.total_len = self.total_len.wrapping_add(pos as u64);
        buffer.len64_padding_be(self.total_len, |block| {
            for (i, &b) in block.iter().enumerate() {
                let idx = i % 32;
                let prev = self.state[(idx + 31) % 32];
                self.state[idx] = self.state[idx]
                    .wrapping_add(b ^ prev)
                    .rotate_left(((i % 7) + 1) as u32)
                    .wrapping_add(i as u8);
            }
        });
        out.copy_from_slice(&self.state);
    }
}

impl Reset for DeterministicHashCore {
    fn reset(&mut self) {
        *self = Self::default();
    }
}

impl AlgorithmName for DeterministicHashCore {
    fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("DeterministicHash")
    }
}

pub type DeterministicHash = CoreWrapper<DeterministicHashCore>;
pub type SampleHmac = Hmac<DeterministicHash>;
pub type SampleHmacCore = HmacCore<DeterministicHash>;
pub type SampleSimpleHmac = SimpleHmac<DeterministicHash>;

pub fn run_contract() {
    let key = b"example-hmac-secret-key";
    let part1 = b"header.";
    let part2 = b"payload";
    let full_msg = b"header.payload";

    // 1. Streaming update and finalize with Hmac
    let mut mac = SampleHmac::new_from_slice(key).expect("Hmac accepts arbitrary key length");
    mac.update(part1);
    mac.update(part2);
    let tag_bytes = mac.finalize().into_bytes();
    assert_eq!(tag_bytes.len(), 32);

    // 2. Chained update (consumes and returns Self) and verify_slice
    SampleHmac::new_from_slice(key)
        .expect("Hmac accepts arbitrary key length")
        .chain_update(full_msg)
        .verify_slice(&tag_bytes)
        .expect("matching message and key must verify");

    // 3. Reject modified tag or message
    let mut bad_tag = tag_bytes;
    bad_tag[0] ^= 0xff;
    let mut bad_verifier =
        SampleHmac::new_from_slice(key).expect("Hmac accepts arbitrary key length");
    bad_verifier.update(full_msg);
    assert!(
        bad_verifier.verify_slice(&bad_tag).is_err(),
        "tampered tag must fail verification"
    );

    // 4. Truncated tag verification (left and right)
    let mut trunc_left =
        SampleHmac::new_from_slice(key).expect("Hmac accepts arbitrary key length");
    trunc_left.update(full_msg);
    trunc_left
        .verify_truncated_left(&tag_bytes[..16])
        .expect("left-truncated tag must verify");

    let mut trunc_right =
        SampleHmac::new_from_slice(key).expect("Hmac accepts arbitrary key length");
    trunc_right.update(full_msg);
    trunc_right
        .verify_truncated_right(&tag_bytes[16..])
        .expect("right-truncated tag must verify");

    // 5. Reuse initialized key state across multiple messages via Clone
    let base_mac = SampleHmac::new_from_slice(key).expect("Hmac accepts arbitrary key length");
    let mut first_mac = base_mac.clone();
    first_mac.update(full_msg);
    let first = first_mac.finalize().into_bytes();

    let mut second_mac = base_mac.clone();
    second_mac.update(full_msg);
    let second = second_mac.finalize().into_bytes();
    assert_eq!(first, tag_bytes);
    assert_eq!(second, tag_bytes);

    // 6. Keys larger than the 64-byte block size are hashed down automatically
    let long_key = [0x42u8; 128];
    let mut long_mac = SampleHmac::new_from_slice(&long_key).expect("long key must be accepted");
    long_mac.update(full_msg);
    let long_tag = long_mac.finalize().into_bytes();

    // 7. SimpleHmac and CoreWrapper<HmacCore> produce identical tags
    let mut simple =
        SampleSimpleHmac::new_from_slice(&long_key).expect("SimpleHmac accepts long key");
    simple.update(full_msg);
    simple
        .verify_slice(&long_tag)
        .expect("SimpleHmac must match Hmac output");

    let core_wrapper: CoreWrapper<SampleHmacCore> =
        CoreWrapper::new_from_slice(&long_key).expect("HmacCore accepts long key");
    let mut core_mac = core_wrapper;
    core_mac.update(full_msg);
    core_mac
        .verify_slice(&long_tag)
        .expect("HmacCore wrapper must match Hmac output");
}
test/contract.rs
fn main() {
    sample_hmac::run_contract();
}

#[test]
fn contract() {
    sample_hmac::run_contract();
}

Ursprungs-Seeder

anonym