2022-05-08 09:47:05 +02:00
|
|
|
use argon2::{Algorithm, Argon2, Params, Version};
|
|
|
|
use password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
|
|
|
|
|
|
|
|
pub trait Encrypt {
|
|
|
|
fn encrypt(&self, salt: &SaltString) -> password_hash::Result<String>;
|
|
|
|
|
|
|
|
fn validate(&self, pass_hash: &crate::PassHash) -> password_hash::Result<()>;
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Encrypt for crate::Password {
|
|
|
|
fn encrypt(&self, salt: &SaltString) -> password_hash::Result<String> {
|
2022-06-07 11:36:01 +02:00
|
|
|
tracing::debug!("Hashing password {:?}", self);
|
2022-05-08 09:47:05 +02:00
|
|
|
Ok(
|
|
|
|
Argon2::new(Algorithm::Argon2id, Version::V0x13, Params::default())
|
|
|
|
.hash_password(self.as_bytes(), &salt)?
|
|
|
|
.to_string(),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn validate(&self, pass_hash: &crate::PassHash) -> password_hash::Result<()> {
|
2022-06-07 11:36:01 +02:00
|
|
|
tracing::debug!("Validating password {:?} {:?}", self, pass_hash);
|
2022-05-08 09:47:05 +02:00
|
|
|
|
|
|
|
Argon2::default().verify_password(
|
|
|
|
self.as_bytes(),
|
|
|
|
&PasswordHash::new(pass_hash.as_str()).expect("Invalid hashed password"),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn print_hash() {
|
|
|
|
use argon2::password_hash::rand_core::OsRng;
|
|
|
|
let salt = SaltString::generate(&mut OsRng);
|
|
|
|
println!("{salt}");
|
|
|
|
}
|