init password generator
This commit is contained in:
+68
@@ -0,0 +1,68 @@
|
||||
use rand::Rng;
|
||||
use rand::rngs::OsRng;
|
||||
use std::fs;
|
||||
|
||||
// enum variant (i keep forgetting the terminology)
|
||||
// enum PasswordType {
|
||||
// RandomChars(usize),
|
||||
// Passphrase(usize, usize),
|
||||
// }
|
||||
|
||||
// non-CTRL chars
|
||||
fn random_ascii() -> u8 {
|
||||
// we definitely want to use the OS for randomness
|
||||
// doesn't require seeding because it is backed by CSPRNG, backed by OS
|
||||
// the OS maintains it's own entropy from mouse movement, hardware noise,etc
|
||||
let mut rng = OsRng;
|
||||
|
||||
// NOT IDEAL FOR CRYPTO/password generation
|
||||
// let range_max = 122; // 125 - 33
|
||||
// let n = rng.next_u32() % range_max; // slightly modulo biased
|
||||
// (n + 33) as u8
|
||||
|
||||
// this function under the hood creates a zone that divides evenly
|
||||
// into the range so we don't encounter modulo bias
|
||||
rng.gen_range(33..125) as u8
|
||||
}
|
||||
|
||||
fn generate_random_chars(len: usize) -> String {
|
||||
// String is a thin wrapper around Vec<u8> so we can expect re-allocation
|
||||
// and copy only when we exceed the capacity of the vector
|
||||
let mut res = String::new();
|
||||
for _ in 0..len {
|
||||
res.push(random_ascii() as char);
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
fn generate_passphrase(phrases: usize, len: usize, words: &Vec<&str>) -> String {
|
||||
let mut res = String::new();
|
||||
let mut count = 0;
|
||||
while count < phrases {
|
||||
let word = random_word(words);
|
||||
if word.is_ascii() { // only add ascii words
|
||||
res.push_str(random_word(words));
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
res.truncate(len); // only works on ascii
|
||||
res
|
||||
}
|
||||
|
||||
fn random_word<'a>(words: &'a Vec<&'a str>) -> &'a str {
|
||||
let mut rng = OsRng;
|
||||
words[rng.gen_range(0..words.len())]
|
||||
}
|
||||
|
||||
|
||||
fn main() {
|
||||
let content = fs::read_to_string("/usr/share/dict/words")
|
||||
.expect("could not read dictionary");
|
||||
let words: Vec<&str> = content.lines().collect();
|
||||
|
||||
let chars = generate_random_chars(20);
|
||||
println!("generated random chars: {}", chars.as_str());
|
||||
|
||||
let phrase = generate_passphrase(3, 20, &words);
|
||||
println!("generated passphrase: {}", phrase.as_str());
|
||||
}
|
||||
Reference in New Issue
Block a user