Add generate_random_sequence() function

This commit is contained in:
silverpill 2023-02-18 21:11:06 +00:00
parent a9cb1c6a83
commit f1972be8db
5 changed files with 30 additions and 11 deletions

View file

@ -1,6 +1,6 @@
use base64; use base64;
use rand;
use rand::prelude::*; use crate::utils::random::generate_random_sequence;
pub fn render_authorization_page() -> String { pub fn render_authorization_page() -> String {
let page = r#"<!DOCTYPE html> let page = r#"<!DOCTYPE html>
@ -41,8 +41,7 @@ pub fn render_authorization_page() -> String {
const ACCESS_TOKEN_SIZE: usize = 20; const ACCESS_TOKEN_SIZE: usize = 20;
pub fn generate_access_token() -> String { pub fn generate_access_token() -> String {
let mut rng = rand::thread_rng(); let value: [u8; ACCESS_TOKEN_SIZE] = generate_random_sequence();
let value: [u8; ACCESS_TOKEN_SIZE] = rng.gen();
base64::encode_config(value, base64::URL_SAFE_NO_PAD) base64::encode_config(value, base64::URL_SAFE_NO_PAD)
} }

View file

@ -1,12 +1,11 @@
use hex; use hex;
use rand;
use rand::prelude::*; use crate::utils::random::generate_random_sequence;
const INVITE_CODE_LENGTH: usize = 32; const INVITE_CODE_LENGTH: usize = 32;
pub fn generate_invite_code() -> String { pub fn generate_invite_code() -> String {
let mut rng = rand::thread_rng(); let value: [u8; INVITE_CODE_LENGTH / 2] = generate_random_sequence();
let value: [u8; INVITE_CODE_LENGTH / 2] = rng.gen();
hex::encode(value) hex::encode(value)
} }

View file

@ -9,4 +9,5 @@ pub mod id;
pub mod markdown; pub mod markdown;
pub mod multibase; pub mod multibase;
pub mod passwords; pub mod passwords;
pub mod random;
pub mod urls; pub mod urls;

View file

@ -1,8 +1,7 @@
use rand::Rng; use super::random::generate_random_sequence;
pub fn hash_password(password: &str) -> Result<String, argon2::Error> { pub fn hash_password(password: &str) -> Result<String, argon2::Error> {
let mut rng = rand::thread_rng(); let salt: [u8; 32] = generate_random_sequence();
let salt: [u8; 32] = rng.gen();
let config = argon2::Config::default(); let config = argon2::Config::default();
argon2::hash_encoded(password.as_bytes(), &salt, &config) argon2::hash_encoded(password.as_bytes(), &salt, &config)
@ -14,3 +13,16 @@ pub fn verify_password(
) -> Result<bool, argon2::Error> { ) -> Result<bool, argon2::Error> {
argon2::verify_encoded(password_hash, password.as_bytes()) argon2::verify_encoded(password_hash, password.as_bytes())
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_verify_password() {
let password = "$test123";
let password_hash = hash_password(password).unwrap();
let result = verify_password(&password_hash, password);
assert_eq!(result.is_ok(), true);
}
}

8
src/utils/random.rs Normal file
View file

@ -0,0 +1,8 @@
use rand::Rng;
pub fn generate_random_sequence<const LEN: usize>() -> [u8; LEN] {
let mut rng = rand::thread_rng();
let mut value = [0u8; LEN];
rng.fill(&mut value[..]);
value
}