pub struct StaticCodex { /* private fields */ }Expand description
Involution-based byte-swap codex backed by a 256-byte lookup table.
The table is held in a crate-internal LockedBytes buffer (mlock’d,
zeroed on drop) since knowledge of the table is equivalent to
knowledge of the transformation.
Implementations§
Source§impl StaticCodex
impl StaticCodex
Sourcepub fn from_swaps(swaps: &[(u8, u8)]) -> Result<Self>
pub fn from_swaps(swaps: &[(u8, u8)]) -> Result<Self>
Construct a codex from a list of swap pairs.
Each (a, b) in swaps means “byte a encodes to b and b
encodes to a.” Bytes not mentioned in any pair are fixed points
(encode to themselves). Self-swaps ((x, x)) are accepted as
no-ops.
§Errors
Returns Error::Codex if a byte appears in
more than one swap pair — that would force the table to disagree
with itself and break the involution property.
§Examples
use key_vault::{Codex, StaticCodex};
// Swap the ASCII digit '0' with '#' and 'A' with '@'.
let codex = StaticCodex::from_swaps(&[(b'0', b'#'), (b'A', b'@')]).unwrap();
assert_eq!(codex.encode(b'0'), b'#');
assert_eq!(codex.encode(b'#'), b'0');
assert_eq!(codex.encode(b'B'), b'B'); // not in any swap, fixed point
// Involution holds:
for byte in 0u8..=255 {
assert_eq!(codex.decode(codex.encode(byte)), byte);
}Sourcepub fn random_involution() -> Result<Self>
pub fn random_involution() -> Result<Self>
Generate a random involution with no fixed points.
Pairs up all 256 bytes uniformly at random and writes the resulting permutation into the lookup table. Every byte transforms to a different byte.
§Errors
Returns Error::Internal if the OS CSPRNG
fails — same failure mode as everywhere else in the crate.
§Examples
use key_vault::{Codex, StaticCodex};
let codex = StaticCodex::random_involution().unwrap();
// Involution: applying it twice returns the original byte.
for byte in 0u8..=255 {
assert_eq!(codex.decode(codex.encode(byte)), byte);
}
// No fixed points: every byte transforms to a different byte.
for byte in 0u8..=255 {
assert_ne!(codex.encode(byte), byte);
}