Skip to main content

krow/
lib.rs

1//! Implementation of the krow key derivation function
2//!
3//! krow is a memory-hard key derivation function designed for password
4//! hashing and key stretching. It uses BLAKE3 and ChaCha20 Core for
5//! cryptographic operations, and provides configurable memory, time,
6//! and security parameters.
7//!
8//! ## Example Usage
9//! ```
10//! use krow;
11//!
12//! let password = b"this is a password";
13//! let salt = b"this is a salt";
14//! let params = krow::Params::default();
15//! let mut dst = [0u8; 32];
16//!
17//! krow::krow(password, salt, None, &params, &mut dst).unwrap();
18//! ```
19
20use blake3::Hasher;
21
22/// Errors for krow.
23pub mod errors;
24mod mix;
25mod params;
26mod traverse;
27
28const KROW: &str = "KROW";
29
30pub use params::Params;
31
32/// Determine a block size from the memory size.
33///
34/// Takes the floored square root of the memory size in bytes,
35/// then rounds down to the nearest power of two divided by 8.
36///
37/// ## Arguments
38/// - `m` - Memory size in KiB
39///
40/// ## Returns
41/// A block size in bytes, with a minimum of 128.
42fn block_size(m: u32) -> usize {
43    // Convert m factor from KiB to bytes
44    let m_bytes = m * 1024;
45    // Floored square root of m_bytes
46    let sqrt = (m_bytes as f64).sqrt().floor() as u32;
47    // Round down to nearest power of two
48    if sqrt == 0 {
49        return 128;
50    }
51    // Find highest set bit position
52    let log2 = 31 - sqrt.leading_zeros();
53    let pow2 = 1u32 << log2;
54    // Divide pow2 by 8, return minimum 128 block size
55    ((pow2 / 8) as usize).max(128)
56}
57
58/// Initialize the krow state from a password, salt, and parameters.
59///
60/// Creates the initial internal state, including memory allocation,
61/// block size, block count, and word count configuration, and commit
62/// derivation from the inputs.
63///
64/// ## Arguments
65/// - `password` - Password bytes.
66/// - `salt` - Salt bytes.
67/// - `context` - Optional context string.
68/// - `params` - krow parameters.
69/// - `output_len` - Desired output length in bytes.
70///
71/// ## Returns
72/// Tuple of (memory, temporary block, commitment, block size,
73/// block count, words per block) if successful,
74/// [`InvalidParams`](crate::errors::InvalidParams) error if
75/// block size validation fails.
76fn krow_init(
77    password: &[u8],
78    salt: &[u8],
79    context: Option<&str>,
80    params: &Params,
81    output_len: u32,
82) -> Result<
83    (Vec<u32>, Vec<u32>, Vec<u8>, usize, usize, usize),
84    errors::InvalidParams,
85> {
86    // Calculate block size
87    let size = block_size(params.m);
88    if size & 127 != 0 {
89        return Err(errors::InvalidParams::BlockSizeInvalid);
90    }
91    // Get block count and words from block size
92    let blocks = (params.m * 1024) as usize / size;
93    let words = size / 4;
94    // Prefix KROW to the context
95    let full_context = match context {
96        Some(ctx) => format!("{}{}", KROW, ctx),
97        None => KROW.to_string(),
98    };
99    // Encode and bind parameters as prefix
100    let mut prefix = [0u8; 16];
101    prefix[0..4].copy_from_slice(&params.m.to_le_bytes());
102    prefix[4..8].copy_from_slice(&params.t.to_le_bytes());
103    prefix[8..12].copy_from_slice(&params.s.to_le_bytes());
104    prefix[12..16].copy_from_slice(&output_len.to_le_bytes());
105    // Initialize BLAKE3 hasher
106    let mut h = Hasher::new_derive_key(&full_context);
107    // Absorb prefix, password, and salt
108    h.update(&prefix);
109    h.update(password);
110    h.update(salt);
111    // Get reader
112    let mut reader = h.finalize_xof();
113    // Read commitment bytes from BLAKE3 XOF
114    let mut commit = vec![0u8; size * 2];
115    reader.fill(&mut commit);
116    // Allocate memory
117    let mut mem = vec![0u32; blocks * words];
118    // Seed blocks 0 and 1 with commitment
119    let seed_len = std::cmp::min(commit.len() / 4, 2 * words);
120    for i in 0..seed_len {
121        mem[i] = u32::from_le_bytes([
122            commit[i * 4],
123            commit[i * 4 + 1],
124            commit[i * 4 + 2],
125            commit[i * 4 + 3],
126        ]);
127    }
128    // Allocate temporary block for mixing
129    let tmp = vec![0u32; words];
130    Ok((mem, tmp, commit, size, blocks, words))
131}
132
133/// Finalize krow derivation and generate output.
134///
135/// Derives the final output key from the accumulator and commitment
136/// using BLAKE3 XOF, then zeros sensitive data.
137///
138/// ## Arguments
139/// - `mem` - Memory state to be zeroed.
140/// - `acc` - Final accumulator bytes.
141/// - `commit` - Commitment bytes.
142/// - `dst` - Destination buffer for output.
143/// - `tmp` - Temporary block to be zeroed.
144fn krow_output(
145    mem: &mut [u32],
146    acc: &[u8],
147    commit: &[u8],
148    dst: &mut [u8],
149    tmp: &mut [u32],
150) {
151    // Initialize BLAKE3 hasher
152    let mut h = Hasher::new_derive_key(&KROW);
153    // Absorb accumulator and commitment
154    h.update(acc);
155    h.update(commit);
156    // Get reader
157    let mut reader = h.finalize_xof();
158    // Read output bytes from BLAKE3 XOF
159    reader.fill(dst);
160    // Zero out sensitive data
161    mem.fill(0);
162    tmp.fill(0);
163}
164
165/// The krow key derivation function.
166///
167/// ## Arguments
168/// - `password` - Password bytes.
169/// - `salt` - Salt bytes.
170/// - `context` - Optional context string.
171/// - `params` - krow parameters.
172/// - `dst` - Destination buffer for derived key.
173///
174/// ## Returns
175/// `Ok(())` if key derivation is successful,
176/// [InvalidParams](crate::errors::InvalidParams) error if:
177/// - Output length is zero or exceeds u32::MAX
178/// - Block size validation fails
179pub fn krow(
180    password: &[u8],
181    salt: &[u8],
182    context: Option<&str>,
183    params: &Params,
184    dst: &mut [u8],
185) -> Result<(), errors::InvalidParams> {
186    // Validate received dst length
187    if dst.is_empty() {
188        return Err(errors::InvalidParams::OutputLenInvalid);
189    }
190    // Assign u32 output length from dst length
191    let output_len = u32::try_from(dst.len())
192        .map_err(|_| errors::InvalidParams::OutputLenInvalid)?;
193    // Initialize from password, salt, context, and params
194    let (mut mem, mut tmp, commit, size, blocks, words) =
195        krow_init(password, salt, context, params, output_len)?;
196    let t = params.t as usize;
197    let s = params.s as usize;
198    // Set fill random dependency and lookup mutability
199    let random = match params.random {
200        Some(val) => val,
201        None => true,
202    };
203    let mutable = match params.mutable {
204        Some(val) => val,
205        None => true,
206    };
207    // Calculate data-independent and data-dependent lookup counts
208    let di_ratio = (100 - s) as f64 / 100.0;
209    let n_di = (blocks as f64 * di_ratio).floor() as usize;
210    let n_dd = blocks - n_di;
211    // Store accumulators from each traversal
212    let mut accumulators: Vec<Vec<u32>> = Vec::with_capacity(t);
213    // Complete t memory traversals
214    for ctr in 0..t {
215        // If not first traversal, apply previous accumulator XOR
216        if ctr > 0 {
217            traverse::xor_acc(
218                &accumulators[ctr - 1],
219                &mut mem,
220                blocks,
221                words,
222                size,
223                ctr,
224            );
225        }
226        // Fill phase - complete one pass over the memory
227        for i in 0..blocks {
228            traverse::fill(
229                &mut mem, blocks, words, size, i, ctr, random, &mut tmp,
230            );
231        }
232        // Lookup phase - initialize accumulator from last block
233        let mut acc = traverse::acc_init(&mem, blocks, words);
234        let offset = ctr * blocks;
235        // Repeat data-independent lookups
236        for i in 0..n_di {
237            traverse::lookup(
238                &mut mem,
239                blocks,
240                words,
241                size,
242                traverse::LookupMode::DI,
243                &mut acc,
244                mutable,
245                Some(offset + i),
246                &mut tmp,
247            );
248        }
249        // Repeat data-dependent lookups
250        for _ in 0..n_dd {
251            traverse::lookup(
252                &mut mem,
253                blocks,
254                words,
255                size,
256                traverse::LookupMode::DD,
257                &mut acc,
258                mutable,
259                None,
260                &mut tmp,
261            );
262        }
263        // Store this traversal's accumulator
264        accumulators.push(acc);
265    }
266    // Generate block-sized finalization of all accumulators
267    let acc_final = traverse::traverse_output(&mut accumulators, size);
268    // Finalize from accumulator and commitment, return derived key
269    Ok(krow_output(&mut mem, &acc_final, &commit, dst, &mut tmp))
270}