bazzar/shared/model/src/encrypt.rs

35 lines
1.1 KiB
Rust
Raw Normal View History

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> {
log::debug!("Hashing password {:?}", self);
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<()> {
log::debug!("Validating password {:?} {:?}", self, pass_hash);
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}");
}