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
//! # C bindings to `Scrypt` key derivation function
//! specified in (RPC 7914)[https://tools.ietf.org/html/rfc7914])

#![cfg_attr(feature = "dev", feature(plugin))]
#![cfg_attr(feature = "dev", plugin(clippy))]
#![allow(non_upper_case_globals)]

use std::mem::size_of;

#[link(name = "scrypt")]
extern "C" {
    pub fn crypto_scrypt(
        passwd: *const u8,
        passwdlen: usize,
        salt: *const u8,
        saltlen: usize,
        N: u64,
        r: u32,
        p: u32,
        buf: *mut u8,
        buflen: usize,
    ) -> ::std::os::raw::c_int;
}

///The Scrypt parameter values
#[derive(Clone, Copy, Debug)]
pub struct ScryptParams {
    /// Number of iterations
    pub n: u64,

    /// Block size for the underlying hash
    pub r: u32,

    /// Parallelization factor
    pub p: u32,
}

impl ScryptParams {
    
    ///Create a new instance of ScryptParams
    /// 
    /// # Arguments:
    /// log_n - The log2 of the Scrypt parameter N
    /// r - The Scrypt parameter r
    /// p - The Scrypt parameter p
    /// 
    pub fn new(n: u64, r: u32, p: u32) -> ScryptParams {
        assert!(r > 0);
        assert!(p > 0);
        assert!(n > 0);
        assert!(size_of::<usize>() >= size_of::<u32>() || (r <= std::usize::MAX as u32 && p < std::usize::MAX as u32));

        ScryptParams { n,r, p }
    }

}

/// Derive fixed size key for given `salt` and `passphrase`
///
/// #Arguments:
/// passwd - password to be derived
/// salt - byte array with salt
/// params - parameters for scrypt into `ScryptParams`
/// output - resulting byte slice
///
pub fn scrypt(passwd: &[u8], salt: &[u8], params: &ScryptParams, output: &mut [u8]) {
    unsafe {
        crypto_scrypt(
            passwd.as_ptr(),
            passwd.len(),
            salt.as_ptr(),
            salt.len(),
            params.n,
            params.r,
            params.p,
            output.as_mut_ptr(),
            output.len(),
        );
    }
}

#[cfg(test)]
mod tests {
    extern crate hex;

    use super::*;
    use tests::hex::{decode, encode};

    const SALT: &str = "fd4acb81182a2c8fa959d180967b374277f2ccf2f7f401cb08d042cc785464b4";

    fn to_bytes<A, T>(slice: &[T]) -> A
    where
        A: AsMut<[T]> + Default,
        T: Clone,
    {
        let mut arr = Default::default();
        <A as AsMut<[T]>>::as_mut(&mut arr).clone_from_slice(slice);
        arr
    }

    #[test]
    fn test_scrypt_128() {
        let salt: [u8; 32] = to_bytes(&decode(SALT).unwrap());
        let passwd = "1234567890";
        let mut buf = [0u8; 16];
        let params = ScryptParams { n: 2, r: 8, p: 1 };

        scrypt(passwd.as_bytes(), &salt, &params, &mut buf);

        assert_eq!("52a5dacfcf80e5111d2c7fbed177113a", encode(buf.as_ref()));
    }

    #[test]
    fn test_scrypt_256() {
        let salt: [u8; 32] = to_bytes(&decode(SALT).unwrap());
        let passwd = "1234567890";
        let mut buf = [0u8; 32];
        let params = ScryptParams { n: 2, r: 8, p: 1 };

        scrypt(passwd.as_bytes(), &salt, &params, &mut buf);

        assert_eq!(
            "52a5dacfcf80e5111d2c7fbed177113a1b48a882b066a017f2c856086680fac7",
            encode(buf.as_ref())
        );
    }

    #[test]
    fn test_scrypt_512() {
        let salt: [u8; 32] = to_bytes(&decode(SALT).unwrap());
        let passwd = "1234567890";
        let mut buf = [0u8; 64];
        let params = ScryptParams { n: 2, r: 8, p: 1 };

        scrypt(passwd.as_bytes(), &salt, &params, &mut buf);

        assert_eq!(
            "52a5dacfcf80e5111d2c7fbed177113a1b48a882b066a017f2c856086680fac7\
             43ae0dd1ba325be061003ec144f1cad75ddbadd7bb01d22970b9904720b6ba27",
            encode(buf.as_ref())
        );
    }
}