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
//! This module provides access to libsodium randomization functions

use super::check_init;

use super::secbuf::SecBuf;

impl SecBuf {
    /// randomize the provided SecBuf
    pub fn randomize(&mut self) {
        check_init();
        unsafe {
            let mut b = self.write_lock();
            rust_sodium_sys::randombytes_buf(raw_ptr_void!(b), b.len());
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_should_randomize_buffer() {
        // Create two random buffers
        let mut buf_a = SecBuf::with_insecure(4);
        buf_a.randomize();
        let mut buf_b = SecBuf::with_insecure(4);
        buf_b.randomize();
        // Should be different (unless we are really lucky...)
        assert!(buf_a.compare(&mut buf_b) != 0);
        // re-randomize
        let mut buf_c = SecBuf::with_insecure(4);
        {
            let a = buf_a.read_lock();
            buf_c.from_array(&a).unwrap();
        }
        assert!(buf_a.compare(&mut buf_c) == 0);
        buf_a.randomize();
        assert!(buf_a.compare(&mut buf_c) != 0);
    }
}