libsodium-rs 0.2.4

A comprehensive, idiomatic Rust wrapper for libsodium, providing a safe and ergonomic API for cryptographic operations
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
//! # Generic Hash Function (BLAKE2b)
//!
//! This module provides a cryptographic hash function based on BLAKE2b that can be used
//! for a wide range of applications. BLAKE2b is a high-performance cryptographic hash
//! function that can be used as a replacement for SHA-2 and SHA-3.
//!
//! ## Features
//!
//! - **Variable output length**: Can produce hashes of any size between `BYTES_MIN` (16) and `BYTES_MAX` (64) bytes
//! - **Keyed hashing**: Supports keyed hashing (MAC) with keys of variable length
//! - **High performance**: Optimized for modern CPUs, faster than SHA-2 and SHA-3
//! - **Incremental hashing**: Supports incremental hashing for processing large data streams
//!
//! ## Security Considerations
//!
//! - BLAKE2b is a cryptographically secure hash function suitable for most applications
//! - For password hashing, use the `crypto_pwhash` module instead
//! - For message authentication codes (MACs), you can use this module with a key
//!
//! ## Example Usage
//!
//! ```rust
//! use libsodium_rs as sodium;
//! use sodium::crypto_generichash;
//! use sodium::ensure_init;
//!
//! // Initialize libsodium
//! ensure_init().expect("Failed to initialize libsodium");
//!
//! // Simple hashing
//! let data = b"Hello, world!";
//! let hash = crypto_generichash::generichash(
//!     data,
//!     None,                            // No key
//!     crypto_generichash::BYTES,       // Default output length (32 bytes)
//! );
//!
//! // Keyed hashing (MAC)
//! let key = sodium::random::bytes(crypto_generichash::KEYBYTES); // 32-byte key
//! let keyed_hash = crypto_generichash::generichash(
//!     data,
//!     Some(&key),                      // With key
//!     crypto_generichash::BYTES,       // Default output length
//! );
//!
//! // Incremental hashing
//! let mut state = crypto_generichash::State::new(None, crypto_generichash::BYTES)
//!     .expect("Failed to initialize hash state");
//! state.update(b"Hello, ");
//! state.update(b"world!");
//! let incremental_hash = state.finalize();
//! ```

use crate::{Result, SodiumError};

// Export the blake2b submodule
pub mod blake2b;
pub use blake2b::*;

/// Minimum number of bytes in a hash output (16)
///
/// This is the minimum length of a hash that can be produced by the generic hash function.
pub const BYTES_MIN: usize = libsodium_sys::crypto_generichash_BYTES_MIN as usize;

/// Maximum number of bytes in a hash output (64)
///
/// This is the maximum length of a hash that can be produced by the generic hash function.
pub const BYTES_MAX: usize = libsodium_sys::crypto_generichash_BYTES_MAX as usize;

/// Default number of bytes in a hash output (32)
///
/// This is the recommended length for most applications, providing a good balance
/// between security and size.
pub const BYTES: usize = libsodium_sys::crypto_generichash_BYTES as usize;

/// Minimum number of bytes in a key (16)
///
/// This is the minimum length of a key that can be used for keyed hashing.
pub const KEYBYTES_MIN: usize = libsodium_sys::crypto_generichash_KEYBYTES_MIN as usize;

/// Maximum number of bytes in a key (64)
///
/// This is the maximum length of a key that can be used for keyed hashing.
pub const KEYBYTES_MAX: usize = libsodium_sys::crypto_generichash_KEYBYTES_MAX as usize;

/// Default number of bytes in a key (32)
///
/// This is the recommended key length for most applications, providing a good balance
/// between security and size.
pub const KEYBYTES: usize = libsodium_sys::crypto_generichash_KEYBYTES as usize;

/// BLAKE2b state for incremental hashing
///
/// This struct represents the state of a BLAKE2b hash computation. It is used for
/// incremental hashing, where data is processed in chunks rather than all at once.
/// This is useful for hashing large files or streams of data.
///
/// ## Example
///
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::crypto_generichash;
/// use sodium::ensure_init;
///
/// // Initialize libsodium
/// ensure_init().expect("Failed to initialize libsodium");
///
/// // Create a new hashing state
/// let mut state = crypto_generichash::State::new(
///     None,                            // No key
///     crypto_generichash::BYTES,       // Default output length (32 bytes)
/// ).expect("Failed to initialize hash state");
///
/// // Update the state with data in chunks
/// state.update(b"Hello, ");
/// state.update(b"world!");
///
/// // Finalize the hash computation
/// let hash = state.finalize();
/// ```
pub struct State {
    state: libsodium_sys::crypto_generichash_state,
    output_len: usize,
}

impl Drop for State {
    fn drop(&mut self) {
        // Securely clear the state when dropped
        unsafe {
            // Use sodium_memzero to clear the state
            libsodium_sys::sodium_memzero(
                &mut self.state as *mut _ as *mut libc::c_void,
                std::mem::size_of::<libsodium_sys::crypto_generichash_state>(),
            );
        }
    }
}

impl State {
    /// Creates a new BLAKE2b hashing state
    ///
    /// This function initializes a new BLAKE2b hashing state for incremental hashing.
    /// It can be used with or without a key, and the output length can be customized.
    ///
    /// ## Algorithm Details
    ///
    /// The generic hash function is currently implemented using BLAKE2b, a fast
    /// cryptographic hash function built on the ChaCha stream cipher. BLAKE2b is
    /// designed to be faster than MD5, SHA-1, SHA-2, and SHA-3, yet is at least
    /// as secure as the latest standard SHA-3.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use libsodium_rs as sodium;
    /// use sodium::crypto_generichash;
    /// use sodium::ensure_init;
    ///
    /// // Initialize libsodium
    /// ensure_init().expect("Failed to initialize libsodium");
    ///
    /// // Create a new hashing state without a key
    /// let mut state = crypto_generichash::State::new(
    ///     None,                            // No key
    ///     crypto_generichash::BYTES,       // Default output length (32 bytes)
    /// ).unwrap();
    ///
    /// // Create a new hashing state with a key (for MAC)
    /// let key = sodium::random::bytes(crypto_generichash::KEYBYTES); // 32-byte key
    /// let mut keyed_state = crypto_generichash::State::new(
    ///     Some(&key),                      // With key
    ///     crypto_generichash::BYTES,       // Default output length
    /// ).unwrap();
    /// ```
    ///
    /// ## Arguments
    ///
    /// * `key` - Optional key for keyed hashing (MAC). If provided, must be between
    ///   `KEYBYTES_MIN` (16) and `KEYBYTES_MAX` (64) bytes.
    /// * `output_len` - Length of the output hash in bytes. Must be between
    ///   `BYTES_MIN` (16) and `BYTES_MAX` (64) bytes.
    ///
    /// ## Returns
    ///
    /// * `Result<Self>` - A new BLAKE2b state or an error
    ///
    /// ## Errors
    ///
    /// Returns an error if:
    /// - The output length is not between `BYTES_MIN` and `BYTES_MAX`
    /// - The key length is not between `KEYBYTES_MIN` and `KEYBYTES_MAX`
    /// - The state initialization fails
    pub fn new(key: Option<&[u8]>, output_len: usize) -> Result<Self> {
        if !(BYTES_MIN..=BYTES_MAX).contains(&output_len) {
            return Err(SodiumError::InvalidInput(format!(
                "Output length must be between {BYTES_MIN} and {BYTES_MAX} bytes"
            )));
        }

        if let Some(key) = key {
            if key.len() < KEYBYTES_MIN || key.len() > KEYBYTES_MAX {
                return Err(SodiumError::InvalidInput(format!(
                    "Key length must be between {KEYBYTES_MIN} and {KEYBYTES_MAX} bytes"
                )));
            }
        }

        let mut state = Self {
            state: unsafe { std::mem::zeroed() },
            output_len,
        };

        let result = match key {
            Some(key) => unsafe {
                libsodium_sys::crypto_generichash_init(
                    &mut state.state,
                    key.as_ptr(),
                    key.len() as libc::size_t,
                    output_len as libc::size_t,
                )
            },
            None => unsafe {
                libsodium_sys::crypto_generichash_init(
                    &mut state.state,
                    std::ptr::null(),
                    0,
                    output_len as libc::size_t,
                )
            },
        };

        if result != 0 {
            return Err(SodiumError::OperationError(
                "Failed to initialize BLAKE2b state".to_string(),
            ));
        }

        Ok(state)
    }

    /// Updates the hash state with more input data
    ///
    /// This function updates the hash state with additional input data.
    /// It can be called multiple times to process data in chunks.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use libsodium_rs as sodium;
    /// use sodium::crypto_generichash;
    /// use sodium::ensure_init;
    ///
    /// // Initialize libsodium
    /// ensure_init().expect("Failed to initialize libsodium");
    ///
    /// // Create a new hashing state
    /// let mut state = crypto_generichash::State::new(
    ///     None,                            // No key
    ///     crypto_generichash::BYTES,       // Default output length (32 bytes)
    /// ).unwrap();
    ///
    /// // Update the state with data in chunks
    /// state.update(b"Hello, ");
    /// state.update(b"world!");
    /// ```
    ///
    /// ## Arguments
    ///
    /// * `input` - Data to add to the hash computation
    pub fn update(&mut self, input: &[u8]) {
        unsafe {
            libsodium_sys::crypto_generichash_update(
                &mut self.state,
                input.as_ptr(),
                input.len() as u64,
            );
        }
    }

    /// Finalizes the hash computation and returns the hash value
    ///
    /// This function finalizes the hash computation and returns the resulting hash value.
    /// After calling this function, the state should not be used anymore.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use libsodium_rs as sodium;
    /// use sodium::crypto_generichash;
    /// use sodium::ensure_init;
    ///
    /// // Initialize libsodium
    /// ensure_init().expect("Failed to initialize libsodium");
    ///
    /// // Create a new hashing state
    /// let mut state = crypto_generichash::State::new(
    ///     None,                            // No key
    ///     crypto_generichash::BYTES,       // Default output length (32 bytes)
    /// ).expect("Failed to initialize hash state");
    ///
    /// // Update the state with data
    /// state.update(b"Hello, world!");
    ///
    /// // Finalize the hash computation
    /// let hash = state.finalize();
    /// ```
    ///
    /// ## Returns
    ///
    /// * `Vec<u8>` - The computed hash
    pub fn finalize(&mut self) -> Vec<u8> {
        let mut out = vec![0u8; self.output_len];

        unsafe {
            libsodium_sys::crypto_generichash_final(
                &mut self.state,
                out.as_mut_ptr(),
                out.len() as libc::size_t,
            );
        }

        out
    }
}

/// Computes a BLAKE2b hash of the input data with an optional key
///
/// This function computes a BLAKE2b hash of the input data, optionally using a key
/// for keyed hashing (MAC). It provides a convenient one-shot interface for hashing
/// data that is already available in memory.
///
/// ## Algorithm Details
///
/// The generic hash function is currently implemented using BLAKE2b, a fast
/// cryptographic hash function built on the ChaCha stream cipher. BLAKE2b is
/// designed to be faster than MD5, SHA-1, SHA-2, and SHA-3, yet is at least
/// as secure as the latest standard SHA-3.
///
/// ## Example
///
/// ```rust
/// use libsodium_rs as sodium;
/// use sodium::crypto_generichash;
/// use sodium::ensure_init;
///
/// // Initialize libsodium
/// ensure_init().expect("Failed to initialize libsodium");
///
/// // Simple hashing
/// let data = b"Hello, world!";
/// let hash = crypto_generichash::generichash(
///     data,
///     None,                            // No key
///     crypto_generichash::BYTES,       // Default output length (32 bytes)
/// );
///
/// // Keyed hashing (MAC)
/// let key = sodium::random::bytes(crypto_generichash::KEYBYTES); // 32-byte key
/// let keyed_hash = crypto_generichash::generichash(
///     data,
///     Some(&key),                      // With key
///     crypto_generichash::BYTES,       // Default output length
/// );
///
/// // Custom output length
/// let short_hash = crypto_generichash::generichash(
///     data,
///     None,                            // No key
///     crypto_generichash::BYTES_MIN,   // Minimum output length (16 bytes)
/// ).expect("Failed to generate hash");
/// assert_eq!(short_hash.len(), crypto_generichash::BYTES_MIN);
/// ```
///
/// ## Arguments
///
/// * `input` - Data to hash
/// * `key` - Optional key for keyed hashing (MAC). If provided, must be between
///   `KEYBYTES_MIN` (16) and `KEYBYTES_MAX` (64) bytes.
/// * `output_len` - Length of the output hash in bytes. Must be between
///   `BYTES_MIN` (16) and `BYTES_MAX` (64) bytes.
///
/// ## Returns
///
/// * `Result<Vec<u8>>` - The computed hash, or an error if parameters are invalid.
///
/// ## Behavior with Invalid Parameters
///
/// If invalid parameters are provided (output length or key length out of range),
/// the function will return an appropriate error.
pub fn generichash(input: &[u8], key: Option<&[u8]>, output_len: usize) -> Result<Vec<u8>> {
    // Validate output length
    if !(BYTES_MIN..=BYTES_MAX).contains(&output_len) {
        return Err(SodiumError::InvalidInput(format!(
            "Output length must be between {BYTES_MIN} and {BYTES_MAX}"
        )));
    }

    // Validate key length if provided
    if let Some(key) = key {
        if key.len() < KEYBYTES_MIN || key.len() > KEYBYTES_MAX {
            return Err(SodiumError::InvalidKey(format!(
                "Key length must be between {KEYBYTES_MIN} and {KEYBYTES_MAX}"
            )));
        }
    }

    // Create state and handle potential errors
    let mut state = State::new(key, output_len)?;
    state.update(input);
    Ok(state.finalize())
}

#[cfg(test)]
mod tests {
    use super::*;
    use ct_codecs::{Encoder, Hex};

    #[test]
    fn test_generichash() {
        let data = b"test data";
        let hash = generichash(data, None, BYTES).unwrap();
        assert_eq!(
            {
                let mut encoded = vec![0u8; hash.len() * 2]; // Hex encoding doubles the length
                let encoded = Hex::encode(&mut encoded, &hash).unwrap();
                std::str::from_utf8(encoded).unwrap().to_string()
            },
            "eab94977a17791d0c089fe9e393261b3ab667cf0e8456632a842d905c468cf65"
        );
    }

    #[test]
    fn test_generichash_with_key() {
        let data = b"test data";
        let key = vec![0u8; KEYBYTES]; // Use a properly sized key
        let hash = generichash(data, Some(&key), BYTES).unwrap();
        assert_eq!(
            {
                let mut encoded = vec![0u8; hash.len() * 2]; // Hex encoding doubles the length
                let encoded = Hex::encode(&mut encoded, &hash).unwrap();
                std::str::from_utf8(encoded).unwrap().to_string()
            },
            "9e34d14a3d2082187f56b14df4e9aaf36b0562e0f842b5b323555192b0c08c22"
        );
    }

    #[test]
    fn test_generichash_incremental() {
        let mut state = State::new(None, BYTES).expect("Failed to create BLAKE2b state");
        state.update(b"test ");
        state.update(b"data");
        let hash = state.finalize();
        let mut encoded = vec![0u8; hash.len() * 2]; // Hex encoding doubles the length
        let encoded = Hex::encode(&mut encoded, &hash).unwrap();
        assert_eq!(
            std::str::from_utf8(encoded).unwrap(),
            "eab94977a17791d0c089fe9e393261b3ab667cf0e8456632a842d905c468cf65"
        );
    }

    #[test]
    fn test_invalid_output_length() {
        // Should return an error for invalid output length
        assert!(generichash(b"test", None, BYTES_MAX + 1).is_err());
        assert!(generichash(b"test", None, BYTES_MIN - 1).is_err());
    }

    #[test]
    fn test_invalid_key_length() {
        let long_key = vec![0u8; KEYBYTES_MAX + 1];
        // Should return an error for invalid key length
        assert!(generichash(b"test", Some(&long_key), BYTES).is_err());
    }
}