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
#[macro_use] extern crate bitflags;
#[macro_use] extern crate lazy_static;

extern crate num_bigint;
extern crate num_integer;
extern crate num_traits;
extern crate ring;

use num_bigint::BigUint;
use num_integer::Integer;
use num_traits::cast::ToPrimitive;

use ring::{digest, digest::Algorithm, hmac, pbkdf2};


bitflags! {
    /// A flag that describes what characters are allowed when generating a password.
    pub struct CharacterSet: u8 {
        const Uppercase = 0b0001;
        const Lowercase = 0b0010;
        const Numbers   = 0b0100;
        const Symbols   = 0b1000;

        const Letters   = Self::Uppercase.bits | Self::Lowercase.bits;
        const All       = Self::Letters.bits | Self::Numbers.bits | Self::Symbols.bits;
    }
}

impl CharacterSet {
    const LOWERCASE: &'static str = "abcdefghijklmnopqrstuvwxyz";
    const UPPERCASE: &'static str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const NUMBERS  : &'static str = "0123456789";
    const SYMBOLS  : &'static str = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";

    /// Return a string that contains all the characters that may be used to generate a password.
    pub fn get_characters(self) -> &'static str {
        match (self.contains(Self::Lowercase), self.contains(Self::Uppercase), self.contains(Self::Numbers), self.contains(Self::Symbols)) {
            (true , true , true , true ) => "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",
            (true , true , true , false) => "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
            (true , true , false, true ) => "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",
            (true , true , false, false) => "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",

            (true , false, true , true ) => "abcdefghijklmnopqrstuvwxyz0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",
            (true , false, true , false) => "abcdefghijklmnopqrstuvwxyz0123456789",
            (true , false, false, true ) => "abcdefghijklmnopqrstuvwxyz!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",
            (true , false, false, false) => Self::LOWERCASE,

            (false, true , true , true ) => "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",
            (false, true , true , false) => "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
            (false, true , false, true ) => "ABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",
            (false, true , false, false) => Self::UPPERCASE,

            (false, false, true , true ) => "0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",
            (false, false, true , false) => Self::NUMBERS,
            (false, false, false, true ) => Self::SYMBOLS,

            _ => ""
        }
    }

    /// Return a vector of all the sets of characters that may be used to generate a password.
    pub fn get_sets(self) -> Vec<&'static str> {
        let mut sets = Vec::with_capacity(4);

        if self.contains(Self::Lowercase) {
            sets.push(Self::LOWERCASE);
        }
        if self.contains(Self::Uppercase) {
            sets.push(Self::UPPERCASE);
        }
        if self.contains(Self::Numbers) {
            sets.push(Self::NUMBERS);
        }
        if self.contains(Self::Symbols) {
            sets.push(Self::SYMBOLS);
        }

        // Ensure we didn't reallocate.
        debug_assert!(sets.capacity() == 4);

        sets
    }
}


/// Generate the salt needed to compute the entropy using a combinaison of the
/// target website, login and counters.
pub fn generate_salt(website: &str, username: &str, counter: u8) -> Vec<u8> {
    let counter_len = if counter < 16 { 1 } else { 2 };
    let mut salt = Vec::with_capacity(website.len() + username.len() + counter_len);

    let cap = salt.capacity();

    salt.extend_from_slice(website.as_bytes());
    salt.extend_from_slice(username.as_bytes());

    if counter < 16 {
        salt.push(HEX[counter as usize]);
    } else {
        salt.push(HEX[( counter & 0b0000_1111      ) as usize]);
        salt.push(HEX[((counter & 0b1111_0000) >> 4) as usize]);
    }

    // Ensure we didn't reallocate.
    debug_assert!(salt.capacity() == cap);

    salt
}

/// Generate the entropy needed to render the end password using a previously computed salt and a master password.
pub fn generate_entropy(master_password: &str, salt: &[u8], algorithm: &'static Algorithm, iterations: u32) -> Vec<u8> {
    let mut out = Vec::with_capacity(32);

    unsafe {
        // Not cool yes, but it allows us to avoid initializing the memory.
        out.set_len(32);
    }

    pbkdf2::derive(algorithm, iterations, salt, master_password.as_bytes(), &mut out);

    out
}

/// Generate a password of the given length using the provided entropy and character sets.
pub fn render_password(entropy: &[u8], charset: CharacterSet, len: u8) -> String {
    assert!(len >= 6 && len <= 64);

    let chars = charset.get_characters().as_bytes();
    let sets  = charset.get_sets();

    let max_len = len as usize - sets.len();
    let chars_len = BigUint::from(chars.len());


    // Generate initial part of the password.
    let mut password_chars = Vec::with_capacity(max_len + sets.len());
    let mut quotient = BigUint::from_bytes_be(entropy);

    for _ in 0..max_len {
        let rem = div_rem(&mut quotient, &chars_len);

        password_chars.push(chars[rem]);
    }


    // Compute some random characters in each set in order to ensure all sets
    // will be used at least once.
    let mut additional_chars = Vec::with_capacity(sets.len());

    for set in &sets {
        let rem = div_rem(&mut quotient, match set.len() {
            10 => &BIGUINT10,
            26 => &BIGUINT26,
            32 => &BIGUINT32,
            _  => unreachable!()
        });

        additional_chars.push(set.as_bytes()[rem]);
    }

    // Ensure we didn't reallocate.
    debug_assert!(additional_chars.capacity() == sets.len());
    debug_assert!(additional_chars.len() == sets.len());


    // Finalize last part of password using previously generated characters.
    let mut password_len = BigUint::from(password_chars.len());

    for ch in additional_chars {
        let rem = div_rem(&mut quotient, &password_len);

        password_chars.insert(rem, ch);
        password_len += &BIGINT1 as &BigUint;
    }

    // Ensure we didn't reallocate.
    debug_assert!(password_chars.capacity() == max_len + sets.len());
    debug_assert!(password_chars.capacity() == password_chars.len());

    unsafe {
        String::from_utf8_unchecked(password_chars)
    }
}

/// Return the SHA-256 fingerprint that corresponds to the given master password.
pub fn get_fingerprint(password: &str) -> hmac::Signature {
    let key = hmac::SigningKey::new(&digest::SHA256, password.as_bytes());

    hmac::sign(&key, b"")
}


lazy_static! {
    static ref BIGINT1  : BigUint = BigUint::from(1u32);
    static ref BIGUINT26: BigUint = BigUint::from(26u32);
    static ref BIGUINT32: BigUint = BigUint::from(32u32);
    static ref BIGUINT10: BigUint = BigUint::from(10u32);
}

const HEX: &[u8] = b"0123456789ABCDEF";

#[inline]
fn div_rem(quot: &mut BigUint, div: &BigUint) -> usize {
    let (new_quot, rem) = quot.div_rem(div);

    *quot = new_quot;

    match rem.to_u64() {
        Some(rem) => rem as usize,
        None => unreachable!()
    }
}