dcrypt-algorithms 1.2.3

Cryptographic primitives for the dcrypt library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
#![cfg_attr(not(feature = "std"), no_std)]

//! Key Derivation Functions with operation pattern and type-level guarantees
//!
//! This module provides implementations of key derivation functions (KDFs)
//! with improved type safety and ergonomic APIs.
//!
/// ## Example usage
///
/// ```
/// # use rand::rngs::OsRng;
/// use dcrypt_algorithms::kdf::{TypedHkdf, KeyDerivationFunction, KdfOperation};
/// use dcrypt_algorithms::hash::Sha256;
///
/// // Create KDF instance
/// let kdf = TypedHkdf::<Sha256>::new();
///
/// // Generate a random salt
/// let salt = TypedHkdf::<Sha256>::generate_salt(&mut OsRng);
///
/// // Traditional API
/// let key1 = kdf.derive_key(
///     b"password123",
///     Some(salt.as_ref()),
///     Some(b"context info"),
///     32
/// ).unwrap();
///
/// // Operation pattern API
/// let key2 = kdf.builder()
///     .with_ikm(b"password123")
///     .with_salt(salt.as_ref())
///     .with_info(b"context info")
///     .with_output_length(32)
///     .derive().unwrap();
///
/// // Derive to fixed-size array
/// let key3: [u8; 32] = kdf.builder()
///     .with_ikm(b"password123")
///     .with_salt(salt.as_ref())
///     .with_info(b"context info")
///     .derive_array().unwrap();
///
/// assert_eq!(key1, key2);
/// assert_eq!(&key1, key3.as_ref());
/// ```
// Conditional imports for no_std
#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(not(feature = "std"))]
#[cfg(feature = "alloc")]
use alloc::vec::Vec;

#[cfg(feature = "std")]
use std::vec::Vec;

#[cfg(feature = "std")]
use std::time::Duration;

#[cfg(not(feature = "std"))]
use core::time::Duration;

use ::core::marker::PhantomData;
use rand::{CryptoRng, RngCore};

// Import the new error types
use crate::error::{Error, Result};
use crate::hash::HashFunction;
use crate::types::Salt;
use zeroize::Zeroize;

pub mod common;
pub mod params;

#[cfg(feature = "alloc")]
pub mod hkdf;

#[cfg(feature = "alloc")]
pub mod pbkdf2;

#[cfg(feature = "alloc")]
pub mod argon2;

pub use common::SecurityLevel;
pub use params::{ParamProvider, PasswordHash};

// Re-exports for convenience
#[cfg(feature = "alloc")]
pub use hkdf::Hkdf;

#[cfg(feature = "alloc")]
pub use pbkdf2::{Pbkdf2, Pbkdf2Params};

#[cfg(feature = "alloc")]
pub use argon2::{Algorithm as Argon2Type, Argon2, Params as Argon2Params};

/// Marker trait for KDF algorithms
pub trait KdfAlgorithm {
    /// Minimum salt size in bytes
    const MIN_SALT_SIZE: usize;

    /// Default output size in bytes
    const DEFAULT_OUTPUT_SIZE: usize;

    /// Static algorithm identifier for compile-time checking
    const ALGORITHM_ID: &'static str;

    /// Returns the KDF algorithm name
    fn name() -> String {
        Self::ALGORITHM_ID.to_string()
    }

    /// Security level provided by this KDF
    fn security_level() -> SecurityLevel;
}

/// Operation for KDF operations with improved type safety
pub trait KdfOperation<'a, A: KdfAlgorithm, T = Vec<u8>>: Sized {
    /// Set the input keying material
    fn with_ikm(self, ikm: &'a [u8]) -> Self;

    /// Set the salt
    fn with_salt(self, salt: &'a [u8]) -> Self;

    /// Set the info/context data
    fn with_info(self, info: &'a [u8]) -> Self;

    /// Set the desired output length
    fn with_output_length(self, length: usize) -> Self;

    /// Execute the key derivation
    fn derive(self) -> Result<T>;

    /// Execute the key derivation into a fixed-size array
    fn derive_array<const N: usize>(self) -> Result<[u8; N]>;
}

/// Common trait for all key derivation functions
pub trait KeyDerivationFunction {
    /// The algorithm this KDF implements
    type Algorithm: KdfAlgorithm;

    /// Salt type with appropriate validation
    type Salt: AsRef<[u8]> + AsMut<[u8]> + Clone;

    /// Creates a new instance of the KDF with default parameters
    fn new() -> Self;

    /// Derives a key using the KDF parameters
    ///
    /// # Arguments
    /// * `input` - Input keying material
    /// * `salt` - Optional salt value
    /// * `info` - Optional context and application-specific information
    /// * `length` - Length of the output key in bytes
    ///
    /// # Returns
    /// The derived key as a byte vector
    #[cfg(feature = "alloc")]
    fn derive_key(
        &self,
        input: &[u8],
        salt: Option<&[u8]>,
        info: Option<&[u8]>,
        length: usize,
    ) -> Result<Vec<u8>>;

    /// Creates a builder for fluent API usage - FIXED: Elided lifetime
    fn builder(&self) -> impl KdfOperation<'_, Self::Algorithm>
    where
        Self: Sized;

    /// Returns the security level of the KDF in bits
    fn security_level() -> SecurityLevel {
        Self::Algorithm::security_level()
    }

    /// Generate a random salt with appropriate size
    fn generate_salt<R: RngCore + CryptoRng>(rng: &mut R) -> Self::Salt;
}

/// Type-level constants for HKDF algorithm
pub enum HkdfAlgorithm<H: HashFunction> {
    /// Phantom field for the hash function
    _Hash(PhantomData<H>),
}

impl<H: HashFunction> KdfAlgorithm for HkdfAlgorithm<H> {
    const MIN_SALT_SIZE: usize = 16;
    const DEFAULT_OUTPUT_SIZE: usize = 32;
    const ALGORITHM_ID: &'static str = "HKDF";

    fn name() -> String {
        format!("{}-{}", Self::ALGORITHM_ID, H::name())
    }

    fn security_level() -> SecurityLevel {
        match H::output_size() * 8 {
            bits if bits >= 512 => SecurityLevel::L256,
            bits if bits >= 384 => SecurityLevel::L192,
            bits if bits >= 256 => SecurityLevel::L128,
            bits => SecurityLevel::Custom(bits as u32 / 2),
        }
    }
}

/// Enhanced HKDF implementation with type-level guarantees
#[cfg(feature = "alloc")]
pub struct TypedHkdf<H: HashFunction + Clone> {
    inner: hkdf::Hkdf<H, 16>, // Use default size of 16
    _phantom: PhantomData<H>,
}

#[cfg(feature = "alloc")]
impl<H: HashFunction + Clone> KeyDerivationFunction for TypedHkdf<H> {
    type Algorithm = HkdfAlgorithm<H>;
    type Salt = Salt<16>; // Updated to use generic Salt with size

    fn new() -> Self {
        Self {
            inner: hkdf::Hkdf::new(),
            _phantom: PhantomData,
        }
    }

    #[cfg(feature = "alloc")]
    fn derive_key(
        &self,
        input: &[u8],
        salt: Option<&[u8]>,
        info: Option<&[u8]>,
        length: usize,
    ) -> Result<Vec<u8>> {
        self.inner.derive_key(input, salt, info, length)
    }

    // FIXED: Elided lifetime
    fn builder(&self) -> impl KdfOperation<'_, Self::Algorithm> {
        HKdfOperation {
            kdf: self,
            ikm: None,
            salt: None,
            info: None,
            length: Self::Algorithm::DEFAULT_OUTPUT_SIZE,
        }
    }

    // FIXED: Removed unnecessary let binding
    fn generate_salt<R: RngCore + CryptoRng>(rng: &mut R) -> Self::Salt {
        Salt::random_with_size(rng, Self::Algorithm::MIN_SALT_SIZE).expect("Salt generation failed")
    }
}

/// HKDF builder implementation
#[cfg(feature = "alloc")]
pub struct HKdfOperation<'a, H: HashFunction + Clone> {
    kdf: &'a TypedHkdf<H>,
    ikm: Option<&'a [u8]>,
    salt: Option<&'a [u8]>,
    info: Option<&'a [u8]>,
    length: usize,
}

#[cfg(feature = "alloc")]
impl<'a, H: HashFunction + Clone> KdfOperation<'a, HkdfAlgorithm<H>> for HKdfOperation<'a, H> {
    fn with_ikm(mut self, ikm: &'a [u8]) -> Self {
        self.ikm = Some(ikm);
        self
    }

    fn with_salt(mut self, salt: &'a [u8]) -> Self {
        self.salt = Some(salt);
        self
    }

    fn with_info(mut self, info: &'a [u8]) -> Self {
        self.info = Some(info);
        self
    }

    fn with_output_length(mut self, length: usize) -> Self {
        self.length = length;
        self
    }

    fn derive(self) -> Result<Vec<u8>> {
        let ikm = self
            .ikm
            .ok_or_else(|| Error::param("ikm", "Input keying material is required"))?;

        self.kdf.derive_key(ikm, self.salt, self.info, self.length)
    }

    fn derive_array<const N: usize>(self) -> Result<[u8; N]> {
        // Ensure the requested size matches
        if self.length != N {
            return Err(Error::Length {
                context: "HKDF output",
                expected: N,
                actual: self.length,
            });
        }

        let vec = self.derive()?;

        // Convert to fixed-size array
        let mut array = [0u8; N];
        array.copy_from_slice(&vec);
        Ok(array)
    }
}

/// Type-level constants for PBKDF2 algorithm
pub enum Pbkdf2Algorithm<H: HashFunction> {
    /// Phantom field for the hash function
    _Hash(PhantomData<H>),
}

impl<H: HashFunction> KdfAlgorithm for Pbkdf2Algorithm<H> {
    const MIN_SALT_SIZE: usize = 16;
    const DEFAULT_OUTPUT_SIZE: usize = 32;
    const ALGORITHM_ID: &'static str = "PBKDF2";

    fn name() -> String {
        format!("{}-{}", Self::ALGORITHM_ID, H::name())
    }

    fn security_level() -> SecurityLevel {
        // PBKDF2 security depends on iterations and hash size
        match H::output_size() * 8 {
            bits if bits >= 512 => SecurityLevel::L128, // Conservative estimate
            bits if bits >= 384 => SecurityLevel::L128,
            bits if bits >= 256 => SecurityLevel::L128,
            bits => SecurityLevel::Custom(bits as u32 / 2),
        }
    }
}

/// Enhanced PBKDF2 implementation with type-level guarantees
#[cfg(feature = "alloc")]
pub struct TypedPbkdf2<H: HashFunction + Clone> {
    inner: pbkdf2::Pbkdf2<H, 16>, // Use default size of 16
    _phantom: PhantomData<H>,
}

#[cfg(feature = "alloc")]
impl<H: HashFunction + Clone> KeyDerivationFunction for TypedPbkdf2<H> {
    type Algorithm = Pbkdf2Algorithm<H>;
    type Salt = Salt<16>; // Updated to use generic Salt with size

    fn new() -> Self {
        Self {
            inner: pbkdf2::Pbkdf2::new(),
            _phantom: PhantomData,
        }
    }

    #[cfg(feature = "alloc")]
    fn derive_key(
        &self,
        input: &[u8],
        salt: Option<&[u8]>,
        info: Option<&[u8]>,
        length: usize,
    ) -> Result<Vec<u8>> {
        self.inner.derive_key(input, salt, info, length)
    }

    // FIXED: Elided lifetime
    fn builder(&self) -> impl KdfOperation<'_, Self::Algorithm> {
        Pbkdf2Builder {
            kdf: self,
            password: None,
            salt: None,
            iterations: 600_000, // OWASP recommended minimum
            length: Self::Algorithm::DEFAULT_OUTPUT_SIZE,
        }
    }

    // FIXED: Removed unnecessary let binding
    fn generate_salt<R: RngCore + CryptoRng>(rng: &mut R) -> Self::Salt {
        Salt::random_with_size(rng, Self::Algorithm::MIN_SALT_SIZE).expect("Salt generation failed")
    }
}

/// PBKDF2 builder implementation
#[cfg(feature = "alloc")]
pub struct Pbkdf2Builder<'a, H: HashFunction + Clone> {
    kdf: &'a TypedPbkdf2<H>,
    password: Option<&'a [u8]>,
    salt: Option<&'a [u8]>,
    iterations: u32,
    length: usize,
}

// FIXED: Elided lifetime in impl block
#[cfg(feature = "alloc")]
impl<H: HashFunction + Clone> Pbkdf2Builder<'_, H> {
    /// Set the number of iterations
    pub fn with_iterations(mut self, iterations: u32) -> Self {
        self.iterations = iterations;
        self
    }
}

#[cfg(feature = "alloc")]
impl<'a, H: HashFunction + Clone> KdfOperation<'a, Pbkdf2Algorithm<H>> for Pbkdf2Builder<'a, H> {
    fn with_ikm(mut self, password: &'a [u8]) -> Self {
        self.password = Some(password);
        self
    }

    fn with_salt(mut self, salt: &'a [u8]) -> Self {
        self.salt = Some(salt);
        self
    }

    fn with_info(self, _info: &'a [u8]) -> Self {
        // PBKDF2 doesn't use info, but we implement for API compatibility
        self
    }

    fn with_output_length(mut self, length: usize) -> Self {
        self.length = length;
        self
    }

    fn derive(self) -> Result<Vec<u8>> {
        let password = self
            .password
            .ok_or_else(|| Error::param("password", "Password is required"))?;
        let salt = self
            .salt
            .ok_or_else(|| Error::param("salt", "Salt is required"))?;

        // Adjust inner Pbkdf2Params
        let mut params = self.kdf.inner.params().clone();
        params.iterations = self.iterations;
        params.key_length = self.length;

        // Use inner implementation
        let mut kdf = self.kdf.inner.clone();
        kdf.set_params(params);

        kdf.derive_key(password, Some(salt), None, self.length)
    }

    fn derive_array<const N: usize>(self) -> Result<[u8; N]> {
        // Ensure the requested size matches
        if self.length != N {
            return Err(Error::Length {
                context: "PBKDF2 output",
                expected: N,
                actual: self.length,
            });
        }

        let vec = self.derive()?;

        // Convert to fixed-size array
        let mut array = [0u8; N];
        array.copy_from_slice(&vec);
        Ok(array)
    }
}

/// Trait for password hashing functions with type-level guarantees
pub trait PasswordHashFunction: KeyDerivationFunction + ParamProvider {
    /// Password type with zeroizing
    type Password: AsRef<[u8]> + AsMut<[u8]> + Clone + Zeroize;

    /// Hashes a password with the configured parameters
    fn hash_password(&self, password: &Self::Password) -> Result<PasswordHash>;

    /// Verifies a password against a hash
    fn verify(&self, password: &Self::Password, hash: &PasswordHash) -> Result<bool>;

    /// Benchmarks the current parameters on this system
    fn benchmark(&self) -> Duration;

    /// Recommends parameters based on a target duration
    fn recommended_params(target_duration: Duration) -> Self::Params;
}