{"id":50984107,"url":"https://github.com/valkyoth/sanitization-rust-crate","last_synced_at":"2026-06-19T17:04:44.378Z","repository":{"id":362685273,"uuid":"1260293407","full_name":"valkyoth/sanitization-rust-crate","owner":"valkyoth","description":"Dependency-free, no_std-first secret memory sanitization for Rust.","archived":false,"fork":false,"pushed_at":"2026-06-05T13:20:37.000Z","size":296,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-06-05T14:06:09.645Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/valkyoth.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE-APACHE","code_of_conduct":null,"threat_model":"THREAT_MODEL.md","audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"github":["eldryoth"],"thanks_dev":"u/gh/eldryoth"}},"created_at":"2026-06-05T10:44:13.000Z","updated_at":"2026-06-05T13:21:00.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/valkyoth/sanitization-rust-crate","commit_stats":null,"previous_names":["valkyoth/sanitization-rust-crate"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/valkyoth/sanitization-rust-crate","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/valkyoth%2Fsanitization-rust-crate","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/valkyoth%2Fsanitization-rust-crate/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/valkyoth%2Fsanitization-rust-crate/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/valkyoth%2Fsanitization-rust-crate/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/valkyoth","download_url":"https://codeload.github.com/valkyoth/sanitization-rust-crate/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/valkyoth%2Fsanitization-rust-crate/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34540570,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-19T02:00:06.005Z","response_time":61,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-06-19T17:04:43.429Z","updated_at":"2026-06-19T17:04:44.367Z","avatar_url":"https://github.com/valkyoth.png","language":"Rust","funding_links":["https://github.com/sponsors/eldryoth","https://thanks.dev/u/gh/eldryoth"],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n  \u003cb\u003eDependency-free, no_std-first secret memory sanitization for Rust.\u003c/b\u003e\u003cbr\u003e\n  Redacted secret containers, safe defaults, explicit volatile wiping, and optional derive ergonomics.\n\u003c/p\u003e\n\n\u003cdiv align=\"center\"\u003e\n  \u003ca href=\"https://docs.rs/sanitization\"\u003eDocs.rs\u003c/a\u003e\n  |\n  \u003ca href=\"THREAT_MODEL.md\"\u003eThreat Model\u003c/a\u003e\n  |\n  \u003ca href=\"SAFETY.md\"\u003eSafety\u003c/a\u003e\n  |\n  \u003ca href=\"SECURITY.md\"\u003eSecurity\u003c/a\u003e\n\u003c/div\u003e\n\n\u003cbr\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://github.com/valkyoth/sanitization-rust-crate\"\u003e\n    \u003cimg src=\"https://raw.githubusercontent.com/valkyoth/sanitization-rust-crate/main/.github/images/sanitization.webp\" alt=\"sanitization Rust crate overview\"\u003e\n  \u003c/a\u003e\n\u003c/p\u003e\n\n# sanitization\n\nDependency-free, `no_std`-first secret memory sanitization for Rust.\n\n`sanitization` is for projects that want a small secret-container layer without\npulling in `zeroize` or a proc-macro dependency by default. The main design is\narchitectural: keep secrets inside redacted, non-`Copy`, non-`Clone`,\nclear-on-drop containers from creation, and use explicit opt-in APIs when an\nordinary buffer must be wiped.\nEvery crate clearing path uses volatile writes by default through one audited\ninternal unsafe boundary.\n\n## Current Status\n\nThe crate is published as stable `1.1.0` on crates.io. It is intended for\nprojects that want dependency-free secret ownership and sanitization by\ndefault, with stronger platform hardening available through explicit feature\nflags.\n\nImplemented now:\n\n- `no_std` default build.\n- zero runtime dependencies.\n- zero external dependencies by default; the optional `derive` feature pulls in\n  the `sanitization-derive` proc-macro sister crate.\n- one audited internal unsafe boundary for default volatile clearing.\n- explicit feature-gated unsafe modules for platform hardening, documented in\n  `SAFETY.md`.\n- `SecretBytes\u003cN\u003e` for fixed-size secrets.\n- `Secret\u003cT\u003e` for custom sanitizable values.\n- `secure_sanitize_struct!` and `secure_drop_struct!` helper macros.\n- optional `SecureSanitize` and `SecureSanitizeOnDrop` derives through the\n  `derive` feature.\n- optional `zeroize` and `subtle` trait interop for projects that already use\n  RustCrypto ecosystem bounds.\n- optional `serde` deserialization for loading secrets from config formats,\n  with redacted serialization.\n- optional `alloc` support with `SecretVec` and `SecretString`.\n- optional platform memory locking with `LockedSecretBytes\u003cN\u003e` on supported\n  Linux, Android, macOS, iOS, Windows, and BSD targets, plus a documented\n  volatile-only WASM compatibility backend behind `wasm-compat`.\n- optional dynamic locked byte storage with `LockedSecretVec` on supported\n  native memory-lock targets.\n- optional pooled locked-memory arenas with `SecretPool\u003cN, SLOTS\u003e` for many\n  same-size fixed secrets under one memory-lock operation on native backends,\n  plus the same pool API on WASM behind `wasm-compat` without host memory\n  locking.\n- optional locked, pooled, and guarded canary integrity checks with\n  `canary-check`.\n- optional OS-CSPRNG canary words with `random-canary`.\n- optional x86_64 assembly-backed equal-length comparison.\n- optional x86_64 volatile-clear plus cache-line eviction helpers.\n- optional explicit multi-pass volatile clear helpers.\n- optional SIMD/vector register scrubbing helpers on x86_64 and AArch64.\n- optional hardware-backed secret provider traits for enclave, HSM, TEE, or\n  platform-keystore integration crates.\n- optional N-of-N XOR split storage with `SplitSecretBytes\u003cN, SHARES\u003e`.\n- no-`std` fixed-size lifetime enforcement with caller-provided monotonic\n  clocks.\n- optional `std` lifetime enforcement with `ExpiringSecretBytes\u003cN\u003e`.\n- optional guard-page dynamic byte storage with `GuardedSecretVec` on supported\n  Linux, Android, macOS, iOS, Windows, and BSD targets.\n- explicit volatile helper APIs for existing ordinary buffers.\n- redacted `Debug` for secret-owning wrapper types.\n- clear-on-drop behavior for crate-owned secret containers.\n- local CI/check script and GitHub workflows.\n- optional bounded Kani proof harnesses for core fixed-size properties.\n- separate optional `sanitization-arrayvec` and `sanitization-bytes` wrapper\n  crates for users that already depend on those ecosystems.\n- threat model and unsafe-boundary documentation.\n\n## Trust Dashboard\n\n| Area | Status |\n| --- | --- |\n| License | `MIT OR Apache-2.0` |\n| MSRV | Rust `1.90.0` |\n| Default target | `no_std` |\n| Runtime dependencies | zero external crates by default |\n| Unsafe policy | `#![deny(unsafe_code)]` at crate root, isolated `#[allow(unsafe_code)]` modules documented in `SAFETY.md` |\n| Clear primitive | volatile writes by default |\n| Heap support | `alloc` feature |\n| Proc macros | optional `derive` feature via `sanitization-derive` |\n| Formal verification | optional bounded Kani harnesses for core properties |\n| Main guarantee | narrow ownership, redaction, and clear-on-drop hygiene |\n| Out of scope | stack-history wiping, global cache secrecy, crash dumps, privileged reads |\n\nRead [THREAT_MODEL.md](THREAT_MODEL.md) and [SAFETY.md](SAFETY.md) before\nusing this crate for high-assurance secret handling.\n\nRead [ROADMAP.md](ROADMAP.md) for the implemented architecture direction and\nremaining high-assurance feature work.\n\n## Rust Version Support\n\nThe minimum supported Rust version is Rust `1.90.0`. New deployments should\nprefer the latest stable Rust.\n\nCompatibility evidence:\n\n| Rust | Local Evidence |\n| --- | --- |\n| `1.90.0` | full check gate |\n| `1.91.0` | `cargo check --all-features` |\n| `1.92.0` | `cargo check --all-features` |\n| `1.93.0` | `cargo check --all-features` |\n| `1.94.0` | `cargo check --all-features` |\n| `1.95.0` | `cargo check --all-features` |\n| `1.96.0` | `cargo check --all-features` |\n\n## Install\n\n```toml\n[dependencies]\nsanitization = \"1.1.0\"\n```\n\nFor heap-backed secret containers:\n\n```toml\n[dependencies]\nsanitization = { version = \"1.1.0\", features = [\"alloc\"] }\n```\n\nThe `unsafe-wipe` feature is kept as a no-op compatibility flag for older\nrelease-candidate dependency declarations. Volatile clearing is now the default.\n\nFor memory-locked fixed-size secrets on supported native platforms:\n\n```toml\n[dependencies]\nsanitization = { version = \"1.1.0\", features = [\"memory-lock\"] }\n```\n\nFor derive macros:\n\n```toml\n[dependencies]\nsanitization = { version = \"1.1.0\", features = [\"derive\"] }\n```\n\nFor optional ecosystem interop:\n\n```toml\n[dependencies]\nsanitization = { version = \"1.1.0\", features = [\"zeroize-interop\", \"subtle-interop\"] }\n```\n\nFor serde-based config loading:\n\n```toml\n[dependencies]\nsanitization = { version = \"1.1.0\", features = [\"serde\", \"alloc\"] }\n```\n\nFor optional ecosystem wrappers, depend on the separate sister crates only when\nyou already use those external libraries:\n\n```toml\n[dependencies]\nsanitization-arrayvec = \"1.1.0\"\nsanitization-bytes = \"1.1.0\"\n```\n\n## Features\n\n| Feature | Default | Purpose |\n| --- | --- | --- |\n| `alloc` | no | Enables `SecretVec` and `SecretString`. |\n| `std` | no | Enables `alloc` plus `ExpiringSecretBytes\u003cN\u003e` lifetime enforcement. |\n| `derive` | no | Re-exports `sanitization-derive` proc macros for `#[derive(SecureSanitize)]` and `#[derive(SecureSanitizeOnDrop)]`. Pulls in proc-macro dependencies only when explicitly enabled. |\n| `serde` | no | Implements serde deserialization for secret loading and redacted serialization for secret-owning wrappers. |\n| `zeroize-interop` | no | Implements `zeroize::Zeroize` and `zeroize::ZeroizeOnDrop` for crate-owned secret containers. |\n| `subtle-interop` | no | Implements `subtle::ConstantTimeEq` for byte-oriented secret containers where the `subtle` trait can represent the comparison. |\n| `memory-lock` | no | Enables `LockedSecretBytes\u003cN\u003e`, native `LockedSecretVec`, `SecretPool\u003cN, SLOTS\u003e`, and locked guarded mappings on supported native targets. On WASM this must be paired with `wasm-compat` and exposes fixed-size volatile-only compatibility backends with no actual memory locking. |\n| `wasm-compat` | no | Explicitly enables reduced-guarantee WASM compatibility backends for `memory-lock` APIs. This does not provide `mlock`, `mprotect`, dump exclusion, or guard pages. |\n| `canary-check` | no | Enables `memory-lock` plus prefix/suffix canary checks for non-empty locked byte mappings, pooled slots, and guarded dynamic mappings. On WASM this must be paired with `wasm-compat` and `random-canary`. |\n| `random-canary` | no | Enables `canary-check` and generates canary words from the OS CSPRNG instead of deriving them from mapping addresses. WASI preview1 uses `random_get`; other bare WASM targets report random generation failure. On WASM it also needs `wasm-compat`. |\n| `asm-compare` | no | Uses an x86_64 inline-assembly loop for equal-length byte comparison. |\n| `cache-flush` | no | Enables explicit x86_64 clear-and-cache-line-evict helpers. |\n| `register-scrub` | no | Enables explicit best-effort SIMD/vector register scrubbing helpers on x86_64 and AArch64. |\n| `guard-pages` | no | Enables `GuardedSecretVec` on supported Linux, Android, macOS, iOS, Windows, and BSD targets. This feature is rejected at compile time on WASM. |\n| `multi-pass-clear` | no | Enables explicit three-pass volatile overwrite helpers for policy or audit compatibility. |\n| `hardware-secrets` | no | Enables dependency-free traits for external hardware-backed secret provider crates. |\n| `split-secret` | no | Enables `SplitSecretBytes\u003cN, SHARES\u003e` N-of-N XOR split storage. |\n| `unsafe-wipe` | no | Compatibility no-op; volatile wiping is default. |\n\nDefault builds are dependency-free and `no_std`.\n\n## WASM Support\n\nThe base containers (`SecretBytes`, `Secret`, `ReadOnceSecret`, and with\n`alloc`, `SecretVec` and `SecretString`) compile on `wasm32` targets.\n`memory-lock` compiles on WASM only when `wasm-compat` is also enabled. That\nfeature pair exposes API-compatible volatile-only backends:\n`LockedSecretBytes\u003cN\u003e` and `SecretPool\u003cN, SLOTS\u003e` own storage inside WASM\nlinear memory and clear it on drop, but no `mlock`, `mmap`, `mprotect`,\n`MADV_DONTDUMP`, or page locking is applied because WASM modules cannot call\nthose host-kernel facilities directly.\n\n```toml\n[dependencies]\nsanitization = { version = \"1.1.0\", features = [\"memory-lock\", \"wasm-compat\"] }\n```\n\n`memory-lock` without `wasm-compat` is rejected at compile time on WASM so\nnative memory-lock expectations are not silently degraded.\n\n`guard-pages` is rejected at compile time on WASM. WASM linear memory has no\nper-page protection API available to the module, so a guard-page-less\n`GuardedSecretVec` would be misleading.\n\n`canary-check` is also rejected at compile time on WASM unless `wasm-compat`\nand `random-canary` are enabled. Deterministic WASM canaries do not have\nASLR-backed mapping entropy, so the crate requires a random canary backend\ninstead of silently providing a predictable integrity word.\n\n`random-canary` uses WASI preview1 `random_get` when targeting\n`wasm32-wasip1`. Bare `wasm32-unknown-unknown`, Emscripten-style WASM, and\nWASI preview2 currently return a `Random` operation error for random canary\nsetup in this dependency-free implementation.\n\nOne caveat matters for all WASM targets: Rust volatile writes survive LLVM\nlowering to WASM, but the WASM specification has no volatile memory operation.\nThe crate uses an `#[inline(never)]` function-pointer boundary on WASM as a\nbest-effort barrier against runtime dead-store removal, but this is weaker than\nnative volatile semantics. Treat WASM clearing as best-effort unless your\nruntime/deployment gives stronger guarantees, such as atomics/shared-memory\nsupport and a runtime that preserves those stores as observable effects.\n\n## Fixed-Size Secrets\n\nUse `SecretBytes\u003cN\u003e` for keys, tokens, nonces, salts, or other fixed-size\nsecret byte arrays that you control from creation.\n\n```rust\nuse sanitization::SecretBytes;\n\nlet mut key = SecretBytes::\u003c32\u003e::from_fn(|index| index as u8);\nlet fallible_key =\n    SecretBytes::\u003c32\u003e::try_from_fn(|index| Ok::\u003cu8, \u0026'static str\u003e(index as u8)).unwrap();\n\nassert_eq!(key.len(), 32);\nassert_eq!(fallible_key.len(), 32);\nassert!(key.constant_time_eq(\u0026[\n    0, 1, 2, 3, 4, 5, 6, 7,\n    8, 9, 10, 11, 12, 13, 14, 15,\n    16, 17, 18, 19, 20, 21, 22, 23,\n    24, 25, 26, 27, 28, 29, 30, 31,\n]));\n\nkey.replace_from_fn(|index| 31 - index as u8);\nkey.try_replace_from_fn(|index| Ok::\u003cu8, \u0026'static str\u003e(index as u8))\n    .unwrap();\nkey.replace_from_array([9; 32]);\n\nkey.transform(|bytes| {\n    for byte in bytes.iter_mut() {\n        *byte ^= 0xA5;\n    }\n});\n\nlet subkey = key.derive::\u003c16\u003e(|input, output| {\n    output.copy_from_slice(\u0026input[..16]);\n});\nassert_eq!(subkey.len(), 16);\n\nkey.into_cleared();\n```\n\nThe type intentionally does not implement `Clone`, `Copy`, `Deref`,\n`AsRef\u003c[u8]\u003e`, or secret-printing `Debug`.\n`SecretBytes\u003cN\u003e` stores `N` bytes inline, and `expose_secret` creates an\nadditional `N`-byte stack copy. On embedded targets or small thread stacks,\nchoose `N` well below the available stack budget or use heap-backed containers.\nFor key derivation, masking, or normalization logic that can operate inside the\ncontainer, prefer `transform`, `try_transform`, `derive`, or `try_derive` so the\noperation does not need an extra `expose_secret` stack copy.\n\n## Expiring Secrets\n\nUse `MonotonicExpiringSecretBytes\u003cN, C\u003e` when fixed-size secrets should reject\naccess after a caller-defined number of monotonic ticks without requiring\n`std`:\n\n```rust\nuse sanitization::{MonotonicClock, MonotonicExpiringSecretBytes};\n\nstruct CounterClock(u64);\n\nimpl MonotonicClock for CounterClock {\n    fn now(\u0026self) -\u003e u64 {\n        self.0\n    }\n}\n\nlet mut key =\n    MonotonicExpiringSecretBytes::\u003c32, _\u003e::from_array([7; 32], CounterClock(10), 300);\n\nassert_eq!(key.try_constant_time_eq(\u0026[7; 32]), Ok(true));\nassert_eq!(key.max_age_ticks(), 300);\n```\n\nThe tick unit is application-defined: milliseconds, RTOS ticks, hardware\ncounter increments, or another monotonic unit. The clock must not move backward\nwithin a secret lifetime window.\n\nEnable `std` when you want the convenience wrapper backed by\n`std::time::Instant`:\n\n```toml\n[dependencies]\nsanitization = { version = \"1.1.0\", features = [\"std\"] }\n```\n\n```rust\nuse sanitization::ExpiringSecretBytes;\nuse std::time::Duration;\n\nlet mut key = ExpiringSecretBytes::\u003c32\u003e::from_array([7; 32], Duration::from_secs(300));\nlet mut generated =\n    ExpiringSecretBytes::\u003c32\u003e::try_from_fn(Duration::from_secs(300), |_| {\n        Ok::\u003cu8, \u0026'static str\u003e(7)\n    })\n    .unwrap();\n\nassert_eq!(key.try_constant_time_eq(\u0026[7; 32]), Ok(true));\nassert_eq!(generated.try_constant_time_eq(\u0026[7; 32]), Ok(true));\n\nkey.try_expose_secret(|bytes| {\n    assert_eq!(bytes.len(), 32);\n}).unwrap();\nkey.try_expose_secret_volatile(|bytes| {\n    assert_eq!(bytes[0], 7);\n}).unwrap();\n\nkey.replace_from_fn(|index| index as u8);\nkey.try_replace_from_fn(|index| Ok::\u003cu8, \u0026'static str\u003e(index as u8))\n    .unwrap();\nkey.into_cleared();\n```\n\nThere is no background timer. Expiration is checked when a fallible access\nmethod is called. If the value has expired, the wrapped secret is cleared before\nreturning `SecretExpiredError`. Full replacement with `replace_from_slice`,\n`replace_from_fn`, or `try_replace_from_fn` restarts the lifetime window for the\nnew value. Fallible generated replacement keeps a still-live old value unchanged\non generator error.\n\n## Copying Secrets Into External APIs\n\nSome cryptographic or protocol APIs require `\u0026[u8]`. Use `expose_secret` for\nshort-lived closure access. The temporary copy is cleared on the normal return\npath and during unwinding, but cannot be cleared if the process aborts.\n\n```rust\nuse sanitization::SecretBytes;\n\nlet key = SecretBytes::\u003c32\u003e::from_array([7; 32]);\n\nlet first_byte = key.expose_secret(|bytes| {\n    // Call the external API here.\n    bytes[0]\n});\n\nassert_eq!(first_byte, 7);\n```\n\n`expose_secret_volatile` is an explicit alias for callers that want the\nvolatile-clearing behavior visible at the call site. Like `expose_secret`, it\ncannot clear the temporary stack copy if the process aborts.\n\n```rust\nuse sanitization::SecretBytes;\n\nlet key = SecretBytes::\u003c32\u003e::from_array([7; 32]);\nlet first_byte = key.expose_secret_volatile(|bytes| bytes[0]);\n\nassert_eq!(first_byte, 7);\n```\n\n## Updating and Clearing Fixed-Size Secrets\n\nMulti-byte mutation and clearing require `\u0026mut self`, so shared references\ncannot observe partially-cleared multi-byte writes.\n\n```rust\nuse sanitization::SecretBytes;\n\nlet mut key = SecretBytes::\u003c32\u003e::zeroed();\n\nkey.copy_from_slice(\u0026[9; 32]).unwrap();\nassert!(key.constant_time_eq(\u0026[9; 32]));\n\nkey.write_byte(0, 1).unwrap();\nassert_eq!(key.read_byte(0), Some(1));\n\nkey.secure_clear();\nassert!(key.constant_time_eq(\u0026[0; 32]));\n```\n\n## Heap Secrets\n\nEnable `alloc` for dynamic secret bytes and secret UTF-8 text.\n\n```rust\nuse sanitization::{SecretString, SecretVec};\n\nlet mut token = SecretString::from_string(String::from(\"bearer-token\"));\nassert_eq!(token.try_with_secret(str::len), Ok(12));\nassert!(token.constant_time_eq(\"bearer-token\"));\n\nlet empty_text = SecretString::default();\nassert!(empty_text.is_empty());\n\ntoken.push_str(\"-v2\");\nassert_eq!(token.try_with_secret(|text| text.ends_with(\"-v2\")), Ok(true));\ntoken.try_with_secret_mut(|text| text.make_ascii_uppercase())\n    .unwrap();\ntoken.replace_from_secret_str(\"rotated-token\");\ntoken.replace_from_string(String::from(\"owned-token\"));\ntoken.replace_from_chars(5, |index| ['t', 'o', 'k', 'e', 'n'][index]);\ntoken\n    .try_replace_from_chars(5, |index| {\n        Ok::\u003cchar, \u0026'static str\u003e(['t', 'o', 'k', 'e', 'n'][index])\n    })\n    .unwrap();\n\nlet mut bytes = SecretVec::from_vec(vec![115, 101, 115, 115, 105, 111, 110]);\nbytes.extend_from_slice(b\"-key\");\nassert_eq!(bytes.with_secret(|value| value.len()), 11);\nassert!(bytes.capacity() \u003e= bytes.len());\nassert!(bytes.constant_time_eq(b\"session-key\"));\n\nlet empty_bytes = SecretVec::default();\nassert!(empty_bytes.is_empty());\n\nbytes.with_secret_mut(|value| value[0] = b'S');\nbytes.replace_from_slice(b\"rotated-session-key\");\nbytes.replace_from_vec(vec![1, 2, 3, 4]);\nbytes.replace_from_fn(16, |index| index as u8);\nbytes\n    .try_replace_from_fn(16, |index| Ok::\u003cu8, \u0026'static str\u003e(index as u8))\n    .unwrap();\n```\n\n`SecretVec` and `SecretString` wipe initialized bytes and spare heap capacity\nbefore freeing their allocations. Use `from_slice` and `from_secret_str` when\nloading borrowed data. Use `from_vec`, `from_string`, `replace_from_vec`, and\n`replace_from_string` to take ownership of existing heap allocations without\ncopying; those allocations become clear-on-drop secret storage. Use\n`replace_from_slice` and `replace_from_secret_str` when rotating from borrowed\ndata. Use `SecretVec::from_fn`, `try_from_fn`, `replace_from_fn`, or\n`try_replace_from_fn` when dynamic bytes can be generated directly into\nclear-on-drop storage. Use `SecretString::from_chars`, `try_from_chars`,\n`replace_from_chars`, or `try_replace_from_chars` when secret UTF-8 text can be\ngenerated as `char` values. Fallible generation clears partial output on error.\n`SecretString::try_with_secret_mut` exposes mutable `\u0026mut str` access without\nallowing safe Rust to invalidate UTF-8. They expose contents through closures\nand redact `Debug`. `capacity()` exposes allocation size metadata for callers\nthat need to size append-heavy flows. `Default` creates an empty heap secret\ncontainer.\n\n## Memory-Locked Secrets\n\nEnable `memory-lock` for fixed-size secrets stored in private platform memory\nand locked with the operating system's resident-memory API on native targets.\nOn WASM, pair `memory-lock` with `wasm-compat` to explicitly request\nAPI-compatible volatile-only storage without host memory locking.\n\n| Platform | Backend | Extra policy |\n| --- | --- | --- |\n| Linux `x86_64`/`aarch64` | raw `mmap`/`mlock` syscalls | `MADV_DONTDUMP` and `MADV_DONTFORK` |\n| Android | system `mmap`/`mlock` ABI | no crate-level dump/fork exclusion |\n| macOS/iOS | system `mmap`/`mlock` ABI | no crate-level dump/fork exclusion |\n| FreeBSD | system `mmap`/`mlock` ABI | `MADV_NOCORE`, no fork exclusion |\n| OpenBSD/NetBSD/DragonFly BSD | system `mmap`/`mlock` ABI | no crate-level dump/fork exclusion |\n| Windows | `VirtualAlloc`/`VirtualLock` | no crate-level dump/fork exclusion |\n| WASM `wasm32-*` | inline WASM-owned storage | API compatibility only; no host memory lock, dump exclusion, or page protection |\n\n```rust\nuse sanitization::LockedSecretBytes;\n\nlet mut key = LockedSecretBytes::\u003c32\u003e::from_fn(|_| 7).unwrap();\nlet fallible_key =\n    LockedSecretBytes::\u003c32\u003e::try_from_fn(|_| Ok::\u003cu8, \u0026'static str\u003e(7)).unwrap();\n\nassert!(key.constant_time_eq(\u0026[7; 32]));\nassert!(fallible_key.constant_time_eq(\u0026[7; 32]));\n\nkey.with_secret(|bytes| {\n    assert_eq!(bytes.len(), 32);\n});\n\nkey.replace_from_slice(\u0026[8; 32]).unwrap();\nkey.replace_from_array([9; 32]).unwrap();\nkey.replace_from_fn(|index| index as u8).unwrap();\nkey.try_replace_from_fn(|index| Ok::\u003cu8, \u0026'static str\u003e(index as u8))\n    .unwrap();\n\nkey.secure_clear();\nassert!(key.constant_time_eq(\u0026[0; 32]));\nkey.into_cleared();\n```\n\n`LockedSecretBytes\u003cN\u003e` does not use the Rust global allocator for the secret\nbytes. It creates a private platform mapping, applies platform hardening policy\nwhere supported by the backend, locks the mapping, volatile-clears the full\nmapping on drop, then unlocks and releases it.\nOn WASM, there is no kernel mapping or memory-lock syscall available to the\nmodule. `LockedSecretBytes\u003cN\u003e` and `SecretPool\u003cN, SLOTS\u003e` therefore compile as\nvolatile-only compatibility containers in WASM linear memory only when\n`wasm-compat` is enabled alongside `memory-lock`. This preserves API-level\nportability for shared code, but it does not prevent host-runtime copies,\nswapping, snapshots, browser memory inspection, or crash dumps.\nUse `from_fn` when bytes can be generated directly into locked or\ncompatibility storage. Use\n`try_from_fn` for fallible generators such as RNG or KDF APIs. Use `from_slice`\nwhen loading bytes from an existing runtime buffer. `from_array` is still\navailable for fixed arrays and clears its owned input array before returning.\nUse `replace_from_array`, `replace_from_slice`, `replace_from_fn`, or\n`try_replace_from_fn` when rotating the whole locked value. Array replacement\nclears its owned input array. Fallible generated replacement keeps the old\nlocked value unchanged on generator error.\n\nUse `LockedSecretVec` when the secret length is known only at runtime and you\nwant native memory-locking without guard pages:\n\n```rust\nuse sanitization::LockedSecretVec;\n\nlet mut token = LockedSecretVec::from_slice(b\"session-key\").unwrap();\nlet generated = LockedSecretVec::try_from_fn(11, |index| {\n    Ok::\u003cu8, \u0026'static str\u003e(b\"session-key\"[index])\n})\n.unwrap();\n\nassert!(token.constant_time_eq(b\"session-key\"));\nassert!(generated.constant_time_eq(b\"session-key\"));\n\ntoken.extend_from_slice(b\"-v2\").unwrap();\ntoken.replace_from_slice(b\"rotated-session-key\").unwrap();\ntoken.replace_from_fn(16, |index| index as u8).unwrap();\ntoken\n    .try_replace_from_fn(16, |index| Ok::\u003cu8, \u0026'static str\u003e(index as u8))\n    .unwrap();\n\ntoken.clear_secret();\nassert!(token.is_empty());\n```\n\n`LockedSecretVec` uses the same native mapping and memory-lock backends as\n`LockedSecretBytes\u003cN\u003e`, but its payload length and capacity are dynamic. It is\nlower overhead than `GuardedSecretVec` because it does not reserve guard pages.\nUse `GuardedSecretVec` instead when page-boundary fault detection matters more\nthan allocation footprint. `LockedSecretVec` is native-only; WASM has no\nhost-kernel memory-lock facility and does not expose this dynamic locked type.\n\nEnable `canary-check` when locked or guarded secrets should detect corruption\nthat reaches either side of the secret data while staying inside the writable\nmapping or pooled slot.\n\n```toml\n[dependencies]\nsanitization = { version = \"1.1.0\", features = [\"canary-check\"] }\n```\n\n```rust\nuse sanitization::LockedSecretBytes;\n\nlet key = LockedSecretBytes::\u003c32\u003e::from_array([7; 32]).unwrap();\n\nlet first = key\n    .expose_secret_checked(|bytes| bytes[0])\n    .unwrap();\n\nassert_eq!(first, 7);\nassert_eq!(key.constant_time_eq_checked(\u0026[7; 32]), Ok(true));\n```\n\nWith `canary-check`, non-empty `LockedSecretBytes\u003cN\u003e` mappings,\n`LockedSecretVec` mappings, and `SecretPool\u003cN, SLOTS\u003e` slots use this layout:\n\n```text\n[ 8-byte canary ][ N-byte secret ][ 8-byte canary ]\n```\n\nExisting exposure APIs such as `with_secret`, `copy_to_slice`, and\n`constant_time_eq` verify the canaries before reading secret bytes. If\ncorruption is detected, the full mapping or slot is volatile-cleared and those\nlegacy APIs panic with a fixed message. Use `expose_secret_checked`,\n`copy_to_slice_checked`, `constant_time_eq_checked`, or `verify_integrity` on\n`LockedSecretBytes\u003cN\u003e`, `expose_secret_checked`, `constant_time_eq_checked`, or\n`verify_integrity` on `LockedSecretVec` and pool slots, when callers need\nexplicit error handling with `CanaryCorruptedError`.\n\nCanaries are derived from the mapping or slot address and a fixed mask on\nnative mapped backends, so they require no RNG or dependency. That deterministic\nmode assumes ASLR or otherwise unpredictable mapping addresses and is best\nunderstood as blind-overwrite detection. If one deterministic canary value is\ndisclosed, the expected value for that mapping or slot is recoverable because\nthe mask is fixed; enable `random-canary` in ASLR-disabled, weak-ASLR,\ncanary-disclosure, or compliance-sensitive environments. On WASM,\n`canary-check` requires `random-canary` because inline storage has no stable\nASLR-backed mapping address. Canaries detect overwrites that reach the canary\nwords; they do not detect corruption entirely inside the secret bytes,\nhistorical copies, or external copies. `LockedSecretBytes\u003cN\u003e`,\n`LockedSecretVec`, and live `SecretPool` slots rewrite canaries after\n`secure_clear` or `clear_secret`, so they remain reusable after manual\nclearing.\n\nEnable `random-canary` when the canary word should come from the operating\nsystem CSPRNG instead of the deterministic address-derived fallback:\n\n```toml\n[dependencies]\nsanitization = { version = \"1.1.0\", features = [\"random-canary\"] }\n```\n\n`random-canary` uses direct platform backends without additional crates: Linux\nand Android `getrandom`, macOS/iOS/BSD `arc4random_buf`, Windows\n`BCryptGenRandom`, and WASI preview1 `random_get`. On WASM, pair it with\n`wasm-compat` because `random-canary` enables the canary/memory-lock\ncompatibility backend. Bare\n`wasm32-unknown-unknown`, Emscripten-style WASM, and WASI preview2 currently\nhave no dependency-free crate-level random import here, so random-canary\nconstruction returns a `Random` operation error on those targets unless a\nfuture backend is added. If OS random generation fails during construction,\nlocked and guarded constructors return a `Random` operation error. For pooled\nslots, use `SecretPool::try_allocate` when callers need explicit RNG error\nhandling; legacy pool allocation helpers panic on RNG failure rather than\nsilently falling back to deterministic canaries.\n\nFor many same-size locked secrets on native targets, use\n`SecretPool\u003cN, SLOTS\u003e` to amortize page-granule memory-locking overhead. This\nis useful on systems with small `RLIMIT_MEMLOCK`/`VirtualLock` quotas because\none locked mapping can hold many slots. On WASM, `SecretPool` keeps the same\nallocation API only when `wasm-compat` is enabled, but stores slots in WASM\nlinear memory and reports `locked_len() == 0`.\n\n```rust\nuse sanitization::SecretPool;\n\nlet pool = SecretPool::\u003c32, 64\u003e::new().unwrap();\n\nlet mut first = pool.allocate_from_array([7; 32]).unwrap();\nlet second = pool.allocate_from_fn(|index| index as u8).unwrap();\n\nassert_eq!(pool.capacity_slots(), 64);\nassert!(first.constant_time_eq(\u0026[7; 32]));\nassert_eq!(second.with_secret(|bytes| bytes[0]), 0);\n\nfirst.replace_from_slice(\u0026[8; 32]).unwrap();\nfirst.secure_clear();\n\ndrop(first); // clears this slot and returns it to the pool\n```\n\nOn native targets, `SecretPool\u003cN, SLOTS\u003e` stores all slots inside one private\nlocked mapping and tracks live slots with an atomic bitmap. On WASM with\n`wasm-compat`, the pool uses inline WASM-owned slot storage instead. A slot\nborrows the pool, so the pool cannot be dropped while slots are live. Dropping\na slot volatile-clears that slot before marking it reusable. Dropping the pool\nvolatile-clears the full native mapping before unlocking and releasing it, or\nclears all WASM-owned slots on WASM.\n\nWith `canary-check`, each non-empty pool slot has its own prefix and suffix\ncanary. Slot exposure, copying, mutation, and comparison verify those canaries\nbefore accessing the payload. Checked slot APIs return `CanaryCorruptedError`;\nlegacy APIs clear the slot and panic.\n\nThis feature is explicit because OS memory locking has platform limits. It can\nfail due to resource limits or policy. Linux `MADV_DONTDUMP` reduces ordinary\nLinux core-dump exposure and `MADV_DONTFORK` reduces accidental fork\ninheritance for the mapping. FreeBSD uses `MADV_NOCORE` for core-dump\nexclusion, but still does not provide fork exclusion. Other non-Linux backends\ncurrently only lock the pages and release them on drop. None of these APIs\nprotect against all crash dump mechanisms, hibernation, debuggers, privileged\nprocess reads, DMA, malicious firmware, or copies made before data enters the\nlocked container.\n\n## Guarded Heap Secrets\n\nEnable `guard-pages` for dynamic byte secrets stored between inaccessible guard\npages on supported Linux, Android, macOS, iOS, Windows, and BSD targets:\n\n```toml\n[dependencies]\nsanitization = { version = \"1.1.0\", features = [\"guard-pages\"] }\n```\n\n```rust\nuse sanitization::GuardedSecretVec;\n\nlet mut token = GuardedSecretVec::from_slice(b\"session-key\").unwrap();\nlet generated = GuardedSecretVec::try_from_fn(11, |index| {\n    Ok::\u003cu8, \u0026'static str\u003e(b\"session-key\"[index])\n})\n.unwrap();\n\nassert!(token.constant_time_eq(b\"session-key\"));\nassert!(generated.constant_time_eq(b\"session-key\"));\ntoken.extend_from_slice(b\"-v2\").unwrap();\nassert_eq!(token.with_secret(|bytes| bytes.len()), 14);\ntoken.replace_from_slice(b\"rotated-session-key\").unwrap();\ntoken.replace_from_fn(16, |index| index as u8).unwrap();\ntoken\n    .try_replace_from_fn(16, |index| Ok::\u003cu8, \u0026'static str\u003e(index as u8))\n    .unwrap();\n\ntoken.clear_secret();\nassert!(token.is_empty());\ntoken.into_cleared();\n```\n\n`GuardedSecretVec` uses a private platform mapping, leaves the pages before and\nafter the writable data region inaccessible, volatile-clears the full writable\nregion on drop, and then releases the allocation. It does not use the Rust\nglobal allocator for the secret bytes. Use `GuardedSecretVec::from_fn` when\nbytes can be generated directly into the guarded mapping; use `try_from_fn` for\nfallible generators. Use `from_slice` when loading bytes from an existing\nruntime buffer.\nUse `replace_from_slice`, `replace_from_fn`, or `try_replace_from_fn` when\nrotating or replacing the entire guarded value. Fallible generated replacement\nkeeps the old value unchanged on generator error. Linux guarded mappings keep\nthe no-libc page granules used by the raw syscall backend: 4 KiB on `x86_64`\nand runtime `AT_PAGESZ` detection from `/proc/self/auxv` on `aarch64`, falling\nback to 64 KiB if detection fails. Android, macOS, iOS, and BSD use\n`getpagesize`; Windows uses `GetSystemInfo`.\n\nWith `canary-check`, `GuardedSecretVec` reserves an 8-byte canary before the\ninitialized payload and another immediately after it. This catches in-region\noverwrites that guard pages cannot catch, such as writes that overrun the\ninitialized length but stay inside the writable capacity. Exposure, mutation,\ngrowth, replacement, and comparison verify canaries first. Use\n`expose_secret_checked`, `constant_time_eq_checked`, or `verify_integrity` when\ncallers need explicit `CanaryCorruptedError` handling.\n\nWhen both `guard-pages` and `memory-lock` are enabled, guarded dynamic secrets\ncan also lock their writable data pages:\n\n```toml\n[dependencies]\nsanitization = { version = \"1.1.0\", features = [\"guard-pages\", \"memory-lock\"] }\n```\n\n```rust\nuse sanitization::GuardedSecretVec;\n\nlet token = GuardedSecretVec::locked_from_slice(b\"session-key\").unwrap();\n\nassert!(token.is_memory_locked());\nassert!(token.constant_time_eq(b\"session-key\"));\n```\n\nLocked guarded mappings preserve the lock state when they grow. Guard pages are\nnot locked because they never contain secret bytes. On Linux, writable data\npages are also marked with `MADV_DONTDUMP` and `MADV_DONTFORK` before locking;\nFreeBSD writable data pages are marked with `MADV_NOCORE` before locking.\nOther non-Linux backends currently lock the writable pages without crate-level\ndump or fork policy. Locking can fail due to OS resource limits or policy, and\nthis does not change the broader memory-lock limits described above.\n`GuardedSecretVec::locked_from_fn` is available for direct byte generation after\nthe writable data pages have been prepared and locked. Use `locked_try_from_fn`\nfor fallible generation into locked guarded storage.\n\nGuard pages are a fault-detection mechanism for crossing outside the mapped\ndata pages. They do not catch logical overreads that stay inside the writable\ndata capacity, and they do not protect external copies made before data enters\nthe guarded container.\n\n## Custom Structs Without Proc Macros\n\nUse `secure_drop_struct!` when the macro should own `Drop` and clear every\nfield on drop:\n\n```rust\nuse sanitization::{secure_drop_struct, SecretBytes};\n\nsecure_drop_struct! {\n    struct SessionCredentials {\n        private_key: SecretBytes\u003c32\u003e,\n        nonce: SecretBytes\u003c12\u003e,\n    }\n}\n\nlet credentials = SessionCredentials {\n    private_key: SecretBytes::from_array([1; 32]),\n    nonce: SecretBytes::from_array([2; 12]),\n};\n\nassert!(credentials.private_key.constant_time_eq(\u0026[1; 32]));\n```\n\nUse `secure_sanitize_struct!` when you need to write a custom `Drop`\nimplementation yourself:\n\n```rust\nuse sanitization::{secure_sanitize_struct, SecretBytes, SecureSanitize};\n\nsecure_sanitize_struct! {\n    struct Credentials {\n        private_key: SecretBytes\u003c32\u003e,\n        nonce: SecretBytes\u003c12\u003e,\n    }\n}\n\nlet mut credentials = Credentials {\n    private_key: SecretBytes::from_array([1; 32]),\n    nonce: SecretBytes::from_array([2; 12]),\n};\n\ncredentials.secure_sanitize();\n```\n\nThese macros are declarative `macro_rules!` macros. They do not require `syn`,\n`quote`, `proc-macro2`, or any compile-time code-generation dependency. They\ncurrently support named-field structs without generics or `where` clauses.\n\nEnable `derive` when you want full struct and enum derive support and accept\nthe explicit proc-macro dependency tradeoff:\n\n```toml\n[dependencies]\nsanitization = { version = \"1.1.0\", features = [\"derive\"] }\n```\n\n```rust\nuse sanitization::{SecretBytes, SecureSanitize, SecureSanitizeOnDrop};\n\n#[derive(SecureSanitize, SecureSanitizeOnDrop)]\nstruct LoginCredentials {\n    password: SecretBytes\u003c32\u003e,\n    session_token: [u8; 32],\n}\n\n#[derive(SecureSanitize)]\nenum KeyMaterial {\n    Symmetric(SecretBytes\u003c32\u003e),\n    Asymmetric {\n        private: SecretBytes\u003c64\u003e,\n        #[sanitization(skip)]\n        public: [u8; 32],\n    },\n    Empty,\n}\n```\n\n`#[derive(SecureSanitize)]` calls `secure_sanitize` on every non-skipped field.\nEvery such field must implement `SecureSanitize`, so adding a new field without\nsanitization support becomes a compiler error. Use `#[sanitization(skip)]` only\nfor fields that are intentionally non-secret or sanitized elsewhere.\n\nThe derive crate is a code generator only. It does not duplicate the wipe\nbackend or secret containers; generated code calls this crate's\n`SecureSanitize` trait. Default builds do not depend on `sanitization-derive`,\n`syn`, `quote`, or `proc-macro2`.\n\nSupported derive attributes are `#[sanitization(skip)]` on fields,\n`#[sanitization(bound = \"...\")]` on fields or containers for explicit generated\n`where` predicates, and\n`#[sanitization(crate = \"::path::to::sanitization\")]` on containers when the\nmain crate is renamed in `Cargo.toml`. The helper attribute intentionally avoids\nthe name `sanitize`, which collides with Rust's experimental built-in sanitizer\nattribute on nightly/Miri. Unions are rejected; implement them manually only\nwhen the active field invariant is documented.\n\nFor `SecureSanitizeOnDrop` on generic structs, put sanitization bounds on the\nstruct declaration itself:\n\n```rust\nuse sanitization::{SecureSanitize, SecureSanitizeOnDrop};\n\n#[derive(SecureSanitize, SecureSanitizeOnDrop)]\nstruct Wrapper\u003cT: SecureSanitize\u003e {\n    inner: T,\n}\n```\n\nThis is a Rust `Drop` restriction: the generated `Drop` impl cannot add a\nstricter `T: SecureSanitize` bound than the struct declaration.\n\n## Ecosystem Interop\n\nThe default build stays dependency-free. Enable interop features only when a\ndownstream API already requires these ecosystem traits:\n\n```toml\n[dependencies]\nsanitization = { version = \"1.1.0\", features = [\"zeroize-interop\", \"subtle-interop\"] }\n```\n\n```rust\nuse sanitization::SecretBytes;\nuse subtle::ConstantTimeEq;\nuse zeroize::Zeroize;\n\nlet mut key = SecretBytes::\u003c32\u003e::from_array([7; 32]);\nlet expected = SecretBytes::\u003c32\u003e::from_array([7; 32]);\n\nassert_eq!(key.ct_eq(\u0026expected).unwrap_u8(), 1);\nkey.zeroize();\n```\n\n`zeroize-interop` implements `Zeroize` and `ZeroizeOnDrop` for this crate's\nowned secret containers by routing to their existing clear methods.\n`subtle-interop` implements `ConstantTimeEq` for self-type comparisons where\nthe `subtle` trait can represent the comparison. Slice and string comparisons\nremain available through this crate's native `constant_time_eq` methods.\n\n## Serde Loading\n\nEnable `serde` when secrets need to be loaded from configuration formats. This\nfeature deserializes into secret containers, but serialization always emits the\nliteral redaction marker `\"\u003credacted\u003e\"` so accidental config dumps or telemetry\ndo not leak secret material.\n\n```toml\n[dependencies]\nsanitization = { version = \"1.1.0\", features = [\"serde\", \"alloc\"] }\nserde = { version = \"1\", features = [\"derive\"] }\n```\n\n```rust\nuse sanitization::{SecretBytes, SecretString};\nuse serde::Deserialize;\n\n#[derive(Deserialize)]\nstruct Config {\n    signing_key: SecretBytes\u003c32\u003e,\n    api_token: SecretString,\n}\n```\n\nThis serde support is intentionally for ingestion. Do not rely on serde\nserialization to export or back up secrets; it redacts by design. For generic\n`Secret\u003cT\u003e` and `ReadOnceSecret\u003cT\u003e`, deserialization uses `T`'s own\n`Deserialize` implementation, so use this crate's leaf types such as\n`SecretBytes\u003cN\u003e`, `SecretVec`, and `SecretString` at secret-bearing fields when\nyou need secret-aware ingestion end to end.\n\n## Generic Secret Wrapper\n\nUse `Secret\u003cT\u003e` when you already have a type that implements `SecureSanitize`\nand you want clear-on-drop plus redacted `Debug`.\n\n```rust\nuse sanitization::{Secret, SecureSanitize};\n\n#[derive(Default)]\nstruct Pair {\n    left: [u8; 16],\n    right: [u8; 16],\n}\n\nimpl SecureSanitize for Pair {\n    fn secure_sanitize(\u0026mut self) {\n        self.left.secure_sanitize();\n        self.right.secure_sanitize();\n    }\n}\n\nlet mut pair = Secret::new(Pair {\n    left: [1; 16],\n    right: [2; 16],\n});\n\npair.with_secret_mut(|value| value.left[0] = 9);\n\nlet mut empty_pair = Secret::\u003cPair\u003e::default();\nempty_pair.with_secret_mut(|value| value.right[0] = 7);\n```\n\n`SecureSanitize` is also implemented for common scalar and standard-library\ncontainer shapes:\n\n- integer types: `u8` through `u128`, `usize`, signed integer equivalents, and\n  `isize`.\n- `bool`, `char`, `f32`, and `f64`.\n- arrays and slices whose element type implements `SecureSanitize`.\n- `Option\u003cT\u003e` and `Result\u003cT, E\u003e` when their contents implement\n  `SecureSanitize`.\n- with `alloc`: `Box\u003cT\u003e`, `Vec\u003cT\u003e`, and `String`.\n\n```rust\nuse sanitization::{Secret, SecureSanitize};\n\nlet mut exponent = Secret::new(0xDEAD_BEEF_u64);\nexponent.with_secret_mut(SecureSanitize::secure_sanitize);\n\nlet mut scalar_words = Secret::new([1_u64, 2, 3, 4]);\nscalar_words.with_secret_mut(SecureSanitize::secure_sanitize);\n\nlet mut maybe_key = Secret::new(Some([7_u8; 32]));\nmaybe_key.with_secret_mut(SecureSanitize::secure_sanitize);\n```\n\nFor `Vec\u003cT\u003e`, the generic implementation sanitizes initialized elements and\nthen clears the vector. It does not wipe arbitrary spare capacity for every\npossible `T`, because spare capacity does not necessarily contain valid `T`\nvalues. For dynamic byte secrets where full allocation capacity matters, use\n`SecretVec`.\n\nOpaque third-party numeric types such as `BigUint` cannot be implemented by\nthis crate without taking a dependency on that type. Wrap them in a local\nnewtype and implement `SecureSanitize` for the newtype, or convert the secret\nmaterial into `SecretBytes\u003cN\u003e`/`SecretVec` at the boundary where possible.\n\n## Read-Once Secrets\n\nUse `ReadOnceSecret\u003cT\u003e` when a value should be accessed once and then cleared.\nThe consume methods take `\u0026self` and atomically mark the wrapper as consumed,\nso repeated access through shared references returns `AlreadyConsumedError`.\n\n```rust\nuse sanitization::{AlreadyConsumedError, ReadOnceSecret, SecretBytes};\n\nlet token = ReadOnceSecret::new(SecretBytes::\u003c4\u003e::from_array([1, 2, 3, 4]));\n\nlet sum = token.consume(|secret| {\n    let mut out = [0; 4];\n    secret.copy_to_slice(\u0026mut out).unwrap();\n    out.iter().copied().fold(0_u8, u8::wrapping_add)\n}).unwrap();\n\nassert_eq!(sum, 10);\nassert_eq!(token.consume(|_| unreachable!()), Err(AlreadyConsumedError));\n```\n\nThe wrapped value is cleared immediately after the first successful closure\nreturns. If the closure unwinds, `Drop` clears during unwinding. Like all\ndestructor-based cleanup, this cannot run if the process aborts.\n\n## Explicit Volatile Wiping\n\nIf a secret already lives in an ordinary buffer, call the volatile helper\ndirectly.\n\n```rust\nuse sanitization::unsafe_wipe::volatile_sanitize_bytes;\n\nlet mut bytes = [0xA5; 32];\nvolatile_sanitize_bytes(\u0026mut bytes);\nassert_eq!(bytes, [0; 32]);\n```\n\nWith `alloc`, `Vec\u003cu8\u003e` and `String` helpers are available:\n\n```rust\nuse sanitization::unsafe_wipe::{volatile_sanitize_string, volatile_sanitize_vec};\n\nlet mut bytes = vec![0xBB; 16];\nvolatile_sanitize_vec(\u0026mut bytes);\nassert!(bytes.is_empty());\n\nlet mut token = String::from(\"secret-token\");\nvolatile_sanitize_string(\u0026mut token);\nassert!(token.is_empty());\n```\n\nFor clear-on-drop volatile behavior, use `VolatileOnDrop`:\n\n```rust\nuse sanitization::unsafe_wipe::VolatileOnDrop;\n\nlet secret = VolatileOnDrop::new([1_u8, 2, 3, 4]);\nassert_eq!(secret.with_secret(|bytes| bytes.len()), 4);\n```\n\n## Multi-Pass Clearing\n\nEnable `multi-pass-clear` when a policy requires explicit multi-pass overwrite\nevidence:\n\n```toml\n[dependencies]\nsanitization = { version = \"1.1.0\", features = [\"multi-pass-clear\"] }\n```\n\n```rust\nuse sanitization::{sanitize_bytes_multi_pass, SecretBytes};\n\nlet mut bytes = [0xA5; 32];\nsanitize_bytes_multi_pass(\u0026mut bytes);\nassert_eq!(bytes, [0; 32]);\n\nlet mut key = SecretBytes::\u003c32\u003e::from_array([7; 32]);\nkey.secure_clear_multi_pass();\nassert!(key.constant_time_eq(\u0026[0; 32]));\n```\n\nThe pattern is zeros, then `0xFF`, then zeros again, all through volatile\nwrites. For ordinary volatile RAM, the default single-pass volatile zeroing is\nthe normal security boundary; multi-pass clearing is provided for compliance\nlanguage and audit compatibility, not because modern DRAM needs it.\n\n## Cache Flush Sanitization\n\nEnable `cache-flush` on x86_64 when a call site explicitly needs volatile\nclearing followed by `clflush`/`mfence` over the affected cache lines:\n\n```toml\n[dependencies]\nsanitization = { version = \"1.1.0\", features = [\"cache-flush\"] }\n```\n\n```rust\nuse sanitization::{cache_flush::cache_flush_sanitize_bytes, SecretBytes};\n\nlet mut scratch = [0xA5; 32];\ncache_flush_sanitize_bytes(\u0026mut scratch);\nassert_eq!(scratch, [0; 32]);\n\nlet mut key = SecretBytes::\u003c32\u003e::from_array([7; 32]);\nkey.secure_clear_and_flush();\nassert!(key.constant_time_eq(\u0026[0; 32]));\n```\n\nWith `alloc`, `cache_flush_sanitize_vec` and `cache_flush_sanitize_string`\nclear the full allocation capacity before flushing the allocation's cache\nlines. With both `guard-pages` and `cache-flush`, `GuardedSecretVec` also\nprovides `clear_secret_and_flush` for its full writable data region. Unsupported\ntargets, Miri, and builds without `cache-flush` do not expose the `cache_flush`\nmodule. This feature reduces post-clear cache residency; it does not protect\nagainst an attacker who can already observe cache timing while the secret is\nlive.\n\n## Assembly Comparison\n\nEnable `asm-compare` on x86_64 when you want equal-length secret comparisons to\ncross an explicit compiler boundary:\n\n```toml\n[dependencies]\nsanitization = { version = \"1.1.0\", features = [\"asm-compare\"] }\n```\n\nThe public API does not change. `SecretBytes\u003cN\u003e`, `SecretVec`, `SecretString`,\nand `LockedSecretBytes\u003cN\u003e` still use their normal `constant_time_eq` methods.\nLength mismatch remains public metadata and returns immediately. Unsupported\ntargets, Miri, and builds without `asm-compare` use the portable Rust fallback.\nThe portable fallback is designed to avoid data-dependent early exit, but it is\nnot a formal hardware-level constant-time guarantee. Use `asm-compare` where it\nis available, or pair this crate with a dedicated constant-time comparison\nlibrary when a protocol requires externally audited timing guarantees.\n\n## Register Scrubbing\n\nEnable `register-scrub` when a call site explicitly wants a best-effort SIMD\nregister clearing boundary after cryptographic code:\n\n```toml\n[dependencies]\nsanitization = { version = \"1.1.0\", features = [\"register-scrub\"] }\n```\n\n```rust\nuse sanitization::register_scrub::scrub_simd_registers;\n\n// Run crypto code that may use vector registers.\nscrub_simd_registers();\n```\n\nOn non-Windows x86_64 this uses `vzeroall` when AVX OS support is available,\nfalling back to caller-saved XMM clears. On Windows x64 it clears XMM0-XMM5 and\nuses `vzeroupper` when AVX OS support is available, preserving ABI-required\nXMM6-XMM15 lower halves. On AArch64 this clears caller-saved V0-V7 and\nV16-V31. Unsupported targets expose a fenced no-op. This is not a whole-process\nregister hygiene guarantee: it cannot clear compiler spills, callee-saved\nvector state, AVX-512 opmask registers, ZMM16-ZMM31, AArch64 V8-V15 upper\nhalves, kernel context-switch buffers, registers used by other threads, or\ncopies already written to memory.\n\n## Split Secrets\n\nEnable `split-secret` for fixed-size N-of-N XOR split storage:\n\n```toml\n[dependencies]\nsanitization = { version = \"1.1.0\", features = [\"split-secret\"] }\n```\n\n```rust\nuse sanitization::SplitSecretBytes;\n\nlet split = SplitSecretBytes::\u003c32, 3\u003e::from_array_with_generator([7; 32], |share, index| {\n    // Documentation-only deterministic mask. Use a real CSPRNG or KDF-backed\n    // random source in production.\n    ((share as u8) \u003c\u003c 4) ^ (index as u8)\n})\n.unwrap();\n\nlet reconstructed = split.reconstruct();\nassert!(reconstructed.constant_time_eq(\u0026[7; 32]));\n```\n\nThis is not Shamir secret sharing and it is not threshold cryptography. Every\nshare is required to reconstruct the secret. The generator closure must produce\ncryptographically random bytes for all mask shares; deterministic examples are\nonly for documentation and tests. Debug builds reject trivially constant mask\nshares as a misuse guardrail, but this heuristic does not validate entropy.\n\n## Hardware Secret Traits\n\nEnable `hardware-secrets` when an external crate needs a dependency-free trait\nsurface for hardware-backed secret providers:\n\n```toml\n[dependencies]\nsanitization = { version = \"1.1.0\", features = [\"hardware-secrets\"] }\n```\n\n```rust\nuse sanitization::hardware::{HardwareSecretHandle, HardwareSecretProvider};\n\nstruct Handle(u64);\nimpl HardwareSecretHandle for Handle {}\n\nstruct Provider;\n\nimpl HardwareSecretProvider for Provider {\n    type Handle = Handle;\n    type Error = ();\n\n    fn seal_from_slice(\u0026self, _secret: \u0026[u8]) -\u003e Result\u003cSelf::Handle, Self::Error\u003e {\n        Ok(Handle(1))\n    }\n\n    fn expose_secret\u003cR, F: FnOnce(\u0026[u8]) -\u003e R\u003e(\n        \u0026self,\n        _handle: \u0026Self::Handle,\n        inspect: F,\n    ) -\u003e Result\u003cR, Self::Error\u003e {\n        Ok(inspect(\u0026[]))\n    }\n\n    fn rotate_from_slice(\n        \u0026self,\n        _handle: \u0026mut Self::Handle,\n        _secret: \u0026[u8],\n    ) -\u003e Result\u003c(), Self::Error\u003e {\n        Ok(())\n    }\n\n    fn destroy(\u0026self, _handle: Self::Handle) -\u003e Result\u003c(), Self::Error\u003e {\n        Ok(())\n    }\n}\n```\n\nThe main crate does not include SGX, Nitro, TPM, HSM, or platform-keystore\nbackends. Those belong in backend crates with their own platform dependencies,\naudits, and threat models.\n\n## Optional Integration Crates\n\nThe main `sanitization` crate remains dependency-free by default. The workspace\nalso publishes small wrapper crates for users that already depend on common\nbuffer libraries:\n\n```toml\n[dependencies]\nsanitization-arrayvec = \"1.1.0\"\nsanitization-bytes = \"1.1.0\"\n```\n\n```rust\nuse sanitization::SecretBytes;\nuse sanitization_arrayvec::SecretArrayVec;\nuse sanitization_bytes::SecretBytesMut;\n\nlet mut keys = SecretArrayVec::\u003cSecretBytes\u003c32\u003e, 4\u003e::new();\nkeys.push(SecretBytes::from_array([7; 32])).unwrap();\n\nlet mut token = SecretBytesMut::with_capacity(16);\ntoken.extend_from_slice(b\"session-token\").unwrap();\ntoken.extend_from_slice(b\"-v2\").unwrap();\n\nkeys.clear_secret();\ntoken.clear_secret();\n```\n\nThese crates use wrapper types because Rust's orphan rules prevent implementing\n`SecureSanitize` directly for external types in a separate crate.\n`SecretBytesMut` treats capacity as fixed after construction and returns an\nerror instead of reallocating on append, because implicit `BytesMut` growth\nwould free an old allocation containing secret bytes before it can be wiped.\nAllocate the maximum expected size up front with `SecretBytesMut::with_capacity`.\n\n## Choosing the Right API\n\n| Use case | Recommended API |\n| --- | --- |\n| Fixed-size key or token | `SecretBytes\u003cN\u003e` |\n| Fixed-size key with no-`std` tick expiry | `MonotonicExpiringSecretBytes\u003cN, C\u003e` |\n| Fixed-size key with access expiry | `ExpiringSecretBytes\u003cN\u003e` with `std` |\n| Fixed-size key that should avoid swap/pagefiles on supported native platforms | `LockedSecretBytes\u003cN\u003e` with `memory-lock` |\n| Dynamic bytes that should avoid swap/pagefiles on supported native platforms | `LockedSecretVec` with `memory-lock` |\n| Fixed-size key needing API-compatible WASM storage | `LockedSecretBytes\u003cN\u003e` with `memory-lock` and `wasm-compat` on WASM, with documented reduced guarantees |\n| Fixed-size locked key with prefix/suffix corruption checks | `LockedSecretBytes\u003cN\u003e` with `canary-check` |\n| Fixed-size locked key with OS-random canary words | `LockedSecretBytes\u003cN\u003e` with `random-canary` |\n| Many same-size fixed keys under native memory-lock quotas | `SecretPool\u003cN, SLOTS\u003e` with `memory-lock` |\n| Many same-size fixed keys with pooled canary checks | `SecretPool\u003cN, SLOTS\u003e` with `canary-check` |\n| Dynamic secret bytes | `SecretVec` with `alloc` |\n| Dynamic bytes with platform guard pages | `GuardedSecretVec` with `guard-pages` |\n| Guarded dynamic bytes with in-region corruption checks | `GuardedSecretVec` with `guard-pages` and `canary-check` |\n| Secret UTF-8 text | `SecretString` with `alloc` |\n| Secret scalar such as `u64` | `Secret\u003cu64\u003e` |\n| Standard compound value | `Secret\u003cT\u003e` where `T: SecureSanitize` |\n| One-time access secret | `ReadOnceSecret\u003cT\u003e` |\n| Custom struct or enum with compiler-generated sanitization | `#[derive(SecureSanitize)]` with `derive` |\n| Custom struct or enum with compiler-generated drop clearing | `#[derive(SecureSanitize, SecureSanitizeOnDrop)]` with `derive` |\n| Custom struct, macro-owned drop | `secure_drop_struct!` |\n| Custom struct, custom drop | `secure_sanitize_struct!` |\n| Existing ordinary buffer | `unsafe_wipe::volatile_sanitize_*` |\n| Generic clear-on-drop wrapper | `Secret\u003cT\u003e` |\n| Explicit x86_64 comparison compiler boundary | `asm-compare` feature |\n| Explicit x86_64 cache-line eviction after clearing | `cache-flush` feature |\n| Explicit SIMD/vector register clearing boundary | `register-scrub` feature |\n| N-of-N fixed-size split storage | `SplitSecretBytes\u003cN, SHARES\u003e` with `split-secret` |\n| Hardware-backed backend crate integration | `hardware-secrets` feature traits |\n| Existing RustCrypto APIs with `zeroize` or `subtle` bounds | `zeroize-interop` or `subtle-interop` features |\n| Config-file secret ingestion | `serde` feature, with redacted serialization |\n| `arrayvec` or `bytes` wrappers | `sanitization-arrayvec` or `sanitization-bytes` |\n\n## Relationship to `zeroize`\n\n`zeroize` is broader and more ergonomic for retrofitting existing types,\nespecially with `#[derive(Zeroize, ZeroizeOnDrop)]`. This crate keeps the core\ncrate dependency-free by default, but now offers an optional\n`sanitization-derive` sister crate behind the `derive` feature for users who\nwant similar compiler-generated struct and enum coverage. When existing\nRustCrypto ecosystem APIs require `zeroize` or `subtle` trait bounds, enable\n`zeroize-interop` or `subtle-interop`; these are explicit opt-ins and are not\npart of the dependency-free default build.\n\nThe intended trade-off:\n\n- use wrapper types from the start for stronger ownership discipline;\n- keep default builds free of proc-macro dependencies;\n- use dependency-free declarative macros for simple custom structs;\n- enable `derive` when compiler-enforced field coverage is worth the explicit\n  proc-macro dependency surface;\n- use explicit volatile APIs only where ordinary memory must be wiped.\n\n## Local Checks\n\nRun the local matrix before changing release-sensitive code:\n\n```bash\nbash scripts/checks.sh\n```\n\nThe check script covers formatting, feature-matrix tests, examples, clippy,\nrelease LLVM IR/assembly verification, optional bounded Kani verification when\n`cargo-kani` is installed, docs with warnings denied, and package listing.\n\nWhen a nightly toolchain with Miri is available, run the interpreter-based\nunsafe-boundary check separately:\n\n```bash\nscripts/verify-miri.sh\n```\n\nTo run the bounded formal harnesses directly:\n\n```bash\nscripts/verify-kani.sh\n```\n\nThese harnesses prove selected fixed-size properties for the volatile clearing\npath, secret clearing visibility, constant-time equality correctness, and\ncapacity arithmetic. They are not a replacement for external review.\n\n## Workspace Layout\n\nThe repository is a multi-crate workspace:\n\n```text\ncrates/sanitization           # main dependency-free-by-default crate\ncrates/sanitization-derive    # optional proc-macro sister crate\ncrates/sanitization-arrayvec  # optional ArrayVec wrapper crate\ncrates/sanitization-bytes     # optional BytesMut wrapper crate\n```\n\nFor crates.io releases, publish the derive crate first, then the main crate,\nthen the integration wrapper crates:\n\n```bash\nscripts/release_1_1.py\n```\n\nThe script runs the local checks, publishes in dependency order, and pauses\nafter `sanitization-derive` and `sanitization` so crates.io can index each\ndependency before the dependent crate is published.\n\nManual order:\n\n```bash\ncd crates/sanitization-derive\ncargo publish\n\ncd ../sanitization\ncargo publish\n\ncd ../sanitization-arrayvec\ncargo publish\n\ncd ../sanitization-bytes\ncargo publish\n```\n\nFrom the repository root, the equivalent package-specific commands are:\n\n```bash\ncargo publish -p sanitization-derive\ncargo publish -p sanitization\ncargo publish -p sanitization-arrayvec\ncargo publish -p sanitization-bytes\n```\n\n## Limits\n\nThis crate reduces accidental retention and accidental exposure. It does not\nprovide complete process-memory secrecy.\n\nImportant limits:\n\n- Volatile wiping requires the crate's internal wipe unsafe boundary; safe Rust\n  alone cannot express volatile byte stores.\n- Safe Rust cannot soundly scrub old stack frames from previous moves.\n- `panic = \"abort\"` prevents destructors from running and prevents closure\n  helpers from clearing temporary stack copies after a panic.\n- Volatile writes prevent the intended clear operation from being optimized away,\n  but cannot clear copies made elsewhere before data enters the container.\n- CPU cache flushes, SIMD clearing, platform memory locking, guard pages, and\n  inline assembly require target-specific unsafe code and are intentionally not\n  part of the default API.\n- It does not protect against swap, hibernation, core dumps, debugger access,\n  `/proc/\u003cpid\u003e/mem`, kernel compromise, DMA, firmware compromise, or copies made\n  by third-party libraries.\n\nSee [THREAT_MODEL.md](THREAT_MODEL.md), [SAFETY.md](SAFETY.md), and\n[SECURITY.md](SECURITY.md) for the security model and maintenance policy.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvalkyoth%2Fsanitization-rust-crate","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvalkyoth%2Fsanitization-rust-crate","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvalkyoth%2Fsanitization-rust-crate/lists"}