From 4d4cec135382941cbd1446d92eb2f1c2fcfdc923 Mon Sep 17 00:00:00 2001 From: StNicolay Date: Sun, 4 Jun 2023 19:54:39 +0300 Subject: [PATCH] Updated password generation functions --- cryptography/src/password_generation.rs | 29 ++++++++++++------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/cryptography/src/password_generation.rs b/cryptography/src/password_generation.rs index 8c84f54..d5a52cd 100644 --- a/cryptography/src/password_generation.rs +++ b/cryptography/src/password_generation.rs @@ -1,6 +1,6 @@ -use arrayvec::{ArrayString, ArrayVec}; +use arrayvec::ArrayString; use rand::{rngs::OsRng, seq::SliceRandom}; -use std::str::from_utf8_unchecked; +use std::array; const CHARS: &[u8] = br##"!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~"##; @@ -16,7 +16,7 @@ bitflags::bitflags! { /// Returns true if the generated master password is valid. /// It checks that it has at least one lowercase, one uppercase, one number and one punctuation char #[inline] -fn check_generated_password(password: &[u8]) -> bool { +fn check_generated_password(password: &[u8; 32]) -> bool { let mut flags = PasswordFlags::empty(); for &byte in password { match byte { @@ -35,19 +35,18 @@ fn check_generated_password(password: &[u8]) -> bool { false } +#[inline] +fn generate_password() -> ArrayString<32> { + loop { + let password: [u8; 32] = array::from_fn(|_| *CHARS.choose(&mut OsRng).unwrap()); + if check_generated_password(&password) { + return ArrayString::from_byte_string(&password).unwrap(); + } + } +} + /// Continuously generates the password until it passes the checks #[inline] pub fn generate_passwords() -> [ArrayString<32>; 10] { - let mut passwords = ArrayVec::new_const(); - while !passwords.is_full() { - let password: ArrayVec = (0..32) - .map(|_| *CHARS.choose(&mut OsRng).unwrap()) - .collect(); - if check_generated_password(&password) { - let mut string = ArrayString::<32>::new_const(); - unsafe { string.push_str(from_utf8_unchecked(&password)) }; - passwords.push(string) - } - } - unsafe { passwords.into_inner_unchecked() } + array::from_fn(|_| generate_password()) }