bazzar/crates/model/src/encrypt.rs

33 lines
1.1 KiB
Rust

use argon2::{Algorithm, Argon2, Params, PasswordHasher, PasswordVerifier, Version};
use password_hash::{PasswordHash, 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> {
// tracing::debug!("Hashing password {:?}", self);
Argon2::new(Algorithm::Argon2id, Version::V0x13, Params::default())
.hash_password(self.as_bytes(), &salt)
.map(|r| r.to_string())
}
fn validate(&self, pass_hash: &crate::PassHash) -> password_hash::Result<()> {
// tracing::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}");
}