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
//! Utility for generating random passwords.
use chbs::{config::BasicConfig, word::WordSampler};
use rand::Rng;
use secrecy::{ExposeSecret, SecretString};
use zxcvbn::{zxcvbn, Entropy};

use crate::{crypto::csprng, Result};

/// Diceware helper functions for generating passphrases.
pub mod diceware {
    use crate::{Error, Result};
    use chbs::{
        config::{BasicConfig, BasicConfigBuilder},
        prelude::*,
        probability::Probability,
        word::{WordList, WordSampler},
    };
    use secrecy::{Secret, SecretString};

    use once_cell::sync::Lazy;

    static WORD_LIST: Lazy<WordList> = Lazy::new(WordList::builtin_eff_large);

    /// Generate a passphrase using the given config.
    pub fn generate_passphrase_config(
        config: &BasicConfig<WordSampler>,
    ) -> Result<(SecretString, f64)> {
        if config.words < 6 {
            return Err(Error::DicewareWordsTooFew(config.words, 6));
        }

        let scheme = config.to_scheme();
        Ok((Secret::new(scheme.generate()), scheme.entropy().bits()))
    }

    /// Generate a diceware passphrase with the given number of words.
    ///
    /// The number of words must be at least six.
    pub fn generate_passphrase_words(
        words: usize,
    ) -> Result<(SecretString, f64)> {
        let config = default_config(words);
        generate_passphrase_config(&config)
    }

    /// Generate a diceware passphrase with six words which is ~171 bits of entropy.
    pub fn generate_passphrase() -> Result<(SecretString, f64)> {
        generate_passphrase_words(6)
    }

    /// Get the default config for diceware passphrase generation.
    pub fn default_config(words: usize) -> BasicConfig<WordSampler> {
        let config = BasicConfigBuilder::default()
            .word_provider(WORD_LIST.sampler())
            .words(words)
            .separator(' ')
            .capitalize_first(Probability::Never)
            .capitalize_words(Probability::Never)
            .build()
            .unwrap();
        config
    }
}

const ROMAN_LOWER: &str = "abcdefghijklmnopqrstuvwxyz";
const ROMAN_UPPER: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const DIGITS: &str = "0123456789";
const PUNCTUATION: &str = "!\"#$%&'()*+,-./:;<=>?@`~\\]^_{}";

/// Measure the entropy in a password.
pub fn measure_entropy(password: &str, user_inputs: &[&str]) -> Entropy {
    zxcvbn(password, user_inputs)
}

/// Generated password result.
#[derive(Debug, Clone)]
pub struct PasswordResult {
    /// The generated password.
    pub password: SecretString,
    /// The computed entropy for the password.
    pub entropy: Entropy,
}

/// Options for password generation.
#[derive(Debug, Clone)]
pub struct PasswordGen {
    length: usize,
    characters: Vec<&'static str>,
    diceware: Option<BasicConfig<WordSampler>>,
}

impl PasswordGen {
    /// Create a new password generator.
    pub fn new(length: usize) -> Self {
        Self {
            length,
            characters: vec![],
            diceware: None,
        }
    }

    /// Create with lowercase and uppercase character sets.
    pub fn new_alpha(length: usize) -> Self {
        Self::new(length).upper().lower()
    }

    /// Create with numeric digits only.
    pub fn new_numeric(length: usize) -> Self {
        Self::new(length).numeric()
    }

    /// Create with numeric digits, uppercase and lowercase
    /// roman letters.
    pub fn new_alpha_numeric(length: usize) -> Self {
        Self::new(length).upper().lower().numeric()
    }

    /// Options using printable ASCII characters.
    pub fn new_ascii_printable(length: usize) -> Self {
        Self::new(length)
            .upper()
            .lower()
            .numeric()
            .ascii_printable()
    }

    /// Create with diceware words.
    pub fn new_diceware(length: usize) -> Self {
        Self::new(length).diceware()
    }

    /// Length of the generated password.
    pub fn len(&self) -> usize {
        self.length
    }

    /// Determine if this generator is zero length.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Use lowercase roman letters.
    pub fn lower(mut self) -> Self {
        self.characters.push(ROMAN_LOWER);
        self
    }

    /// Use uppercase roman letters.
    pub fn upper(mut self) -> Self {
        self.characters.push(ROMAN_UPPER);
        self
    }

    /// Use numeric digits.
    pub fn numeric(mut self) -> Self {
        self.characters.push(DIGITS);
        self
    }

    /// Use printable ASCII punctuation characters.
    pub fn ascii_printable(mut self) -> Self {
        self.characters.push(PUNCTUATION);
        self
    }

    /// Use diceware words.
    pub fn diceware(mut self) -> Self {
        self.diceware = Some(diceware::default_config(self.len()));
        self
    }

    /// Generate a random password.
    pub fn one(&self) -> Result<PasswordResult> {
        let password = if let Some(config) = &self.diceware {
            let (passphrase, _) =
                diceware::generate_passphrase_config(config)?;
            passphrase
        } else {
            let rng = &mut csprng();
            let len = self.characters.iter().fold(0, |acc, s| acc + s.len());
            let mut characters = Vec::with_capacity(len);
            for chars in &self.characters {
                let mut list = chars.chars().collect();
                characters.append(&mut list);
            }
            let mut password = String::new();
            for _ in 0..self.length {
                password.push(characters[rng.gen_range(0..len)]);
            }
            SecretString::new(password)
        };
        let entropy = zxcvbn(password.expose_secret(), &[]);
        let result = PasswordResult { password, entropy };
        Ok(result)
    }

    /// Generate multiple passwords
    pub fn many(&self, count: usize) -> Result<Vec<PasswordResult>> {
        let mut results = Vec::new();
        for _ in 0..count {
            results.push(self.one()?);
        }
        Ok(results)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use anyhow::Result;
    use secrecy::ExposeSecret;

    #[test]
    fn passgen_alpha() -> Result<()> {
        let generator = PasswordGen::new_alpha(12);
        let result = generator.one()?;
        assert_eq!(generator.len(), result.password.expose_secret().len());
        Ok(())
    }

    #[test]
    fn passgen_numeric() -> Result<()> {
        let generator = PasswordGen::new_numeric(12);
        let result = generator.one()?;
        assert_eq!(generator.len(), result.password.expose_secret().len());
        Ok(())
    }

    #[test]
    fn passgen_alphanumeric() -> Result<()> {
        let generator = PasswordGen::new_alpha_numeric(12);
        let result = generator.one()?;
        assert_eq!(generator.len(), result.password.expose_secret().len());
        Ok(())
    }

    #[test]
    fn passgen_ascii_printable() -> Result<()> {
        let generator = PasswordGen::new_ascii_printable(12);
        let result = generator.one()?;
        assert_eq!(generator.len(), result.password.expose_secret().len());
        Ok(())
    }

    #[test]
    fn passgen_ascii_printable_long() -> Result<()> {
        let generator = PasswordGen::new_ascii_printable(32);
        let result = generator.one()?;
        assert_eq!(generator.len(), result.password.expose_secret().len());
        Ok(())
    }

    #[test]
    fn passgen_diceware() -> Result<()> {
        let generator = PasswordGen::new_diceware(6);
        let result = generator.one()?;
        let words: Vec<String> = result
            .password
            .expose_secret()
            .split(' ')
            .map(|s| s.to_owned())
            .collect();
        assert_eq!(generator.len(), words.len());
        Ok(())
    }

    #[test]
    fn passgen_generate() -> Result<()> {
        let generator = PasswordGen::new_ascii_printable(12);
        let count = 5;
        let passwords = generator.many(count)?;
        assert_eq!(count, passwords.len());
        for result in passwords {
            assert_eq!(
                generator.len(),
                result.password.expose_secret().len()
            );
        }
        Ok(())
    }
}