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
//! An easy to use library for generating passwords.
//!
//! A number of distributions are available to generate passwords from
//! including alphanumeric and diceware style.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#![cfg_attr(feature = "strict", feature(plugin))]
#![cfg_attr(feature = "strict", plugin(clippy))]
#![cfg_attr(feature = "strict", deny(warnings))]

#[macro_use]
extern crate lazy_static;
extern crate rand;

pub mod ascii;
pub mod diceware;

use rand::{thread_rng, Rng};
use ascii::Ascii;
use rand::distributions::Alphanumeric;
use diceware::diceware_distribution::Diceware;
use diceware::eff_distribution::EffDiceware;

/// A password generator. Once `Qwerty` has been initialized
/// with the desired password properties the terminal function
/// `generate` can be called to get a password.
///
/// # Examples
///
/// ```
/// use qwerty::{Qwerty, Distribution};
/// let password = Qwerty::new(Distribution::Alphanumeric, 32).generate();
/// ```
pub struct Qwerty {
    distribution: Distribution,
    num_tokens: usize,
}

impl Qwerty {
    /// Create a new `Qwerty` password generator.
    ///
    /// # Examples
    ///
    /// The following will create a password generator that uses
    /// the `Ascii` uniform distribution over the ASCII charachters,
    /// numbers, and symbols. It also sets the password length to be
    /// 25. Once the terminal function `generate()` is called it will
    /// return a password with these properties.
    ///
    /// ```
    /// use qwerty::{Qwerty, Distribution};
    ///
    /// let ascii_password_generator = Qwerty::new(Distribution::Ascii, 25);
    /// let password = ascii_password_generator.generate();
    /// println!("{}", password);
    /// ```
    pub fn new(distribution: Distribution, num_tokens: usize) -> Qwerty {
        Qwerty {
            distribution,
            num_tokens,
        }
    }

    /// Generate a password.
    ///
    /// # Examples
    ///
    /// The following will generate a password using the EFF diceware
    /// long word list that is 8 words long.
    ///
    /// ```
    /// use qwerty::{Qwerty, Distribution};
    ///
    /// let password = Qwerty::new(Distribution::EffDiceware, 8).generate();
    /// println!("{}", password);
    /// ```
    pub fn generate(&self) -> String {
        match self.distribution {
            Distribution::Alphanumeric => alphanumeric_password(self.num_tokens),
            Distribution::Ascii => ascii_password(self.num_tokens),
            Distribution::Diceware => diceware_password(self.num_tokens),
            Distribution::EffDiceware => eff_diceware_password(self.num_tokens),
        }
    }
}

/// The types of distributions available to select passwords from.
#[derive(Debug)]
pub enum Distribution {
    /// Alphanumeric uniform distribution.
    ///
    /// Samples a `char`, uniformly distributed over ASCII letters, and numbers:
    /// a-z, A-Z, and 0-9.
    Alphanumeric,

    /// Ascii uniform distribution.
    ///
    /// Sample a `char`, uniformly distributed over ASCII letters, numbers, and symbols:
    /// a-z, A-Z, 0-9 and !"#$%&'()*+,-./:;<=>?@`\~[]{}^_| .
    Ascii,

    /// A uniform distribution over the standard diceware wordlist.
    ///
    /// The complete list contains 7776 short words, abbreviations and
    /// easy-to-remember character strings. The average length of each
    /// word is about 4.2 characters. The biggest words are six characters
    /// long.
    Diceware,

    /// A uniform distribution over the standard diceware wordlist.
    ///
    /// The complete list contains 7776 short words, abbreviations and
    /// easy-to-remember character strings. The list has an average length
    /// of 7.0 characters per word, and 12.9 bits of entropy per word,
    /// yielding an efficiency of 1.8 bits of entropy per character.
    EffDiceware,
}

fn diceware_tokens(num: usize) -> Vec<&'static [u8]> {
    let diceware_tokens: Vec<&'static [u8]> =
        thread_rng().sample_iter(&Diceware).take(num).collect();
    diceware_tokens
}

fn diceware_password(num: usize) -> String {
    let diceware_password: Vec<u8> = diceware_tokens(num)
        .iter()
        .cloned()
        .flat_map(|word| word.iter().cloned())
        .collect();
    (*String::from_utf8_lossy(&diceware_password)).to_owned()
}

fn eff_diceware_tokens(num: usize) -> Vec<&'static [u8]> {
    let eff_diceware_tokens: Vec<&'static [u8]> =
        thread_rng().sample_iter(&EffDiceware).take(num).collect();
    eff_diceware_tokens
}

fn eff_diceware_password(num: usize) -> String {
    let eff_diceware_password: Vec<u8> = eff_diceware_tokens(num)
        .iter()
        .cloned()
        .flat_map(|word| word.iter().cloned())
        .collect();
    (*String::from_utf8_lossy(&eff_diceware_password)).to_owned()
}

fn ascii_tokens(num: usize) -> Vec<char> {
    let ascii_tokens: Vec<char> = thread_rng().sample_iter(&Ascii).take(num).collect();
    ascii_tokens
}

fn ascii_password(num: usize) -> String {
    let ascii_password: String = ascii_tokens(num).into_iter().collect();
    ascii_password
}

fn alphanumeric_tokens(num: usize) -> Vec<char> {
    let ascii_tokens: Vec<char> = thread_rng().sample_iter(&Alphanumeric).take(num).collect();
    ascii_tokens
}

fn alphanumeric_password(num: usize) -> String {
    let ascii_password: String = alphanumeric_tokens(num).into_iter().collect();
    ascii_password
}

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

    // -------------------------------------------------------------------------
    // Token number tests
    //
    // Token types differ between alphanumeric type passwords and
    // the diceware word based. These ensure that the number of
    // tokens generated are handled properly for each.
    // -------------------------------------------------------------------------

    #[test]
    fn diceware_token_number() {
        assert_eq!(0, diceware_tokens(0).iter().count());
        assert_eq!(1, diceware_tokens(1).iter().count());
        assert_eq!(8, diceware_tokens(8).iter().count());
        assert_eq!(42, diceware_tokens(42).iter().count());
        assert_eq!(4000, diceware_tokens(4000).iter().count());
    }

    #[test]
    fn eff_diceware_token_number() {
        assert_eq!(0, eff_diceware_tokens(0).iter().count());
        assert_eq!(1, eff_diceware_tokens(1).iter().count());
        assert_eq!(8, eff_diceware_tokens(8).iter().count());
        assert_eq!(42, eff_diceware_tokens(42).iter().count());
        assert_eq!(4000, eff_diceware_tokens(4000).iter().count());
    }

    #[test]
    fn ascii_token_number() {
        assert_eq!(0, ascii_tokens(0).iter().count());
        assert_eq!(1, ascii_tokens(1).iter().count());
        assert_eq!(8, ascii_tokens(8).iter().count());
        assert_eq!(42, ascii_tokens(42).iter().count());
        assert_eq!(4000, ascii_tokens(4000).iter().count());
    }

    #[test]
    fn alphanumeric_token_number() {
        assert_eq!(0, alphanumeric_tokens(0).iter().count());
        assert_eq!(1, alphanumeric_tokens(1).iter().count());
        assert_eq!(8, alphanumeric_tokens(8).iter().count());
        assert_eq!(42, alphanumeric_tokens(42).iter().count());
        assert_eq!(4000, alphanumeric_tokens(4000).iter().count());
    }

    // -------------------------------------------------------------------------
    // Password length tests
    //
    // While the length of the `char` based generators should be equivalent
    // to the number of tokens requested the word list based generators
    // are tested within their min/max bounds.
    //
    // Diceware bounds:
    // - Min: 1 characters
    // - Max: 6 characters
    //
    // Eff Diceware bounds:
    // - Min: 3 characters
    // - Max: 9 characters
    // -------------------------------------------------------------------------

    fn diceware_bounds(num_tokens: usize, count: usize) -> bool {
        let min = num_tokens;
        let max = num_tokens * 6;
        if (count >= min) && (count <= max) {
            return true;
        }
        false
    }

    fn eff_diceware_bounds(num_tokens: usize, count: usize) -> bool {
        let min = num_tokens * 3;
        let max = num_tokens * 9;
        if (count >= min) && (count <= max) {
            return true;
        }
        false
    }

    #[test]
    fn diceware_password_length() {
        assert!(diceware_bounds(0, diceware_password(0).chars().count()));
        assert!(diceware_bounds(1, diceware_password(1).chars().count()));
        assert!(diceware_bounds(42, diceware_password(42).chars().count()));
        assert!(diceware_bounds(
            4000,
            diceware_password(4000).chars().count()
        ));
    }

    #[test]
    fn eff_diceware_password_length() {
        assert!(eff_diceware_bounds(
            0,
            eff_diceware_password(0).chars().count()
        ));
        assert!(eff_diceware_bounds(
            1,
            eff_diceware_password(1).chars().count()
        ));
        assert!(eff_diceware_bounds(
            42,
            eff_diceware_password(42).chars().count()
        ));
        assert!(eff_diceware_bounds(
            4000,
            eff_diceware_password(4000).chars().count()
        ));
    }

    #[test]
    fn ascii_password_length() {
        assert_eq!(0, ascii_password(0).chars().count());
        assert_eq!(1, ascii_password(1).chars().count());
        assert_eq!(8, ascii_password(8).chars().count());
        assert_eq!(42, ascii_password(42).chars().count());
        assert_eq!(4000, ascii_password(4000).chars().count());
    }

    #[test]
    fn alphanumeric_password_length() {
        assert_eq!(0, alphanumeric_password(0).chars().count());
        assert_eq!(1, alphanumeric_password(1).chars().count());
        assert_eq!(8, alphanumeric_password(8).chars().count());
        assert_eq!(42, alphanumeric_password(42).chars().count());
        assert_eq!(4000, alphanumeric_password(4000).chars().count());
    }
}