mpw 0.2.1

Rust implementation of the Masterpassword algorithm.
Documentation
//! This crate implements the [Masterpassword
//! algorithm](http://masterpasswordapp.com/algorithm.html) in Rust.

extern crate byteorder;
extern crate crypto;
extern crate hmac;
extern crate sha2;

use byteorder::{BigEndian, WriteBytesExt};

const KEY_LEN: usize = 64;
const SEED_LEN: usize = 32;
const MAGIC: &'static [u8] = b"com.lyndir.masterpassword";
const VEC_IO_ERROR_STR: &'static str = "IO error while writing to Vec";

/// A character class representing numbers.
pub const CHAR_CLASS_N: &'static [char] = &['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
/// A template for generating 4 digit PIN codes.
pub const TEMPLATES_PIN: &'static [Template] =
    &[&[CHAR_CLASS_N, CHAR_CLASS_N, CHAR_CLASS_N, CHAR_CLASS_N]];

/// A template is a slice of character slices. It describes which characters
/// are valid at each position in a password.
///
/// For example, a template `[[AB], [DC]]` describes a password where the first
/// character is either an `A` or a `B`, and the second character is either a
/// `D` or a `C`.
pub type Template<'a> = &'a [&'a [char]];

/// A seed can be turned in a password.
#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash, Ord, PartialOrd)]
pub struct Seed {
    /// The raw representation of the seed.
    pub raw: [u8; SEED_LEN],
}

impl Seed {
    /// Turns this password into a password following one of the supplied
    /// templates.
    ///
    /// The template may not describe a password longer than 31 characters.
    pub fn create_password(&self, templates: &[Template]) -> String {
        for template in templates {
            debug_assert!(template.len() < SEED_LEN);
        }

        let template = templates[self.raw[0] as usize % templates.len()];
        assert!(template.len() < SEED_LEN);

        let mut password = String::with_capacity(template.len());

        for (characters, &seed) in template.iter().zip(self.raw[1..].iter()) {
            password.push(characters[seed as usize % characters.len()]);
        }

        return password;
    }
}

/// Generates the seeds needed for password creation.
pub struct SeedGenerator {
    key: [u8; KEY_LEN],
}

impl SeedGenerator {
    /// Create a new seed generator that will generate seeds using the supplied
    /// identity and master password.
    ///
    /// The identity will usually be the real name of the person who we are
    /// generating seeds for.
    pub fn new(identity: &[u8], password: &[u8]) -> Self {
        use crypto::scrypt::{scrypt, ScryptParams};

        const LOG_N: u8 = 15;
        const R: u32 = 8;
        const P: u32 = 2;

        let mut key = [0; KEY_LEN];
        let mut seed = MAGIC.to_vec();
        seed.write_u32::<BigEndian>(identity.len() as u32)
            .expect(VEC_IO_ERROR_STR);
        seed.extend_from_slice(identity);

        scrypt(password, &seed, &ScryptParams::new(LOG_N, R, P), &mut key);

        SeedGenerator { key: key }
    }

    /// Creates a new seed that can be turned into a passsword.
    ///
    /// The message should be what we're generating a password for. This will
    /// usually be the domain name of a website. The counter makes it so
    /// multiple passwords per message are possible.
    pub fn calculate_password_seed(&self, message: &[u8], counter: u32) -> Seed {
        use hmac::{Hmac, Mac};
        use sha2::Sha256;

        let mut hmac = Hmac::<Sha256>::new(&self.key);

        let mut input = MAGIC.to_vec();
        input
            .write_u32::<BigEndian>(message.len() as u32)
            .expect(VEC_IO_ERROR_STR);
        input.extend(message);
        input
            .write_u32::<BigEndian>(counter)
            .expect(VEC_IO_ERROR_STR);

        hmac.input(&input);

        Seed {
            raw: {
                let mut array_seed = [0; SEED_LEN];
                let result = hmac.result();
                let slice_seed = result.code();

                for (left, right) in array_seed.iter_mut().zip(slice_seed.iter()) {
                    *left = *right;
                }
                array_seed
            },
        }
    }
}

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

    #[test]
    pub fn test_pins() {
        const TESTS: &'static [(&'static str, &'static str, &'static str, u32, &'static str)] = &[
            ("John Doe", "password", "tomato", 1, "5914"),
            ("John Doe", "password", "potato", 1, "7329"),
            ("John Doe", "password", "carrot", 1, "0762"),
            ("John Doe", "password", "tomato", 2, "2525"),
            ("John Doe", "password", "potato", 2, "9390"),
            ("John Doe", "password", "carrot", 2, "2750"),
            ("Nice Guy", "verysafe", "tomato", 2, "6380"),
            ("Nice Guy", "verysafe", "potato", 2, "1749"),
            ("Nice Guy", "verysafe", "carrot", 2, "7846"),
        ];

        for test in TESTS {
            let &(identity, master, message, counter, result) = test;

            let generator = SeedGenerator::new(identity.as_bytes(), master.as_bytes());
            let generated = generator
                .calculate_password_seed(message.as_bytes(), counter)
                .create_password(TEMPLATES_PIN);
            assert_eq!(generated, result);
        }
    }
}