use crate::aliases::{Aes256Key32, PasswordString, Salt16};
use crate::constants::DEFAULT_PBKDF2_ITERATIONS;
use crate::derive_pbkdf2_key;
use crate::error::AescryptError;
#[derive(Debug)]
pub struct Pbkdf2Builder {
iterations: u32,
salt: Salt16, }
impl Pbkdf2Builder {
#[must_use]
pub fn new() -> Self {
Self {
iterations: DEFAULT_PBKDF2_ITERATIONS,
salt: Salt16::from_random(),
}
}
#[must_use]
pub fn with_iterations(mut self, iterations: u32) -> Self {
self.iterations = iterations.max(1);
self
}
#[must_use]
pub fn with_salt(mut self, salt: impl Into<[u8; 16]>) -> Self {
self.salt = Salt16::from(salt.into());
self
}
#[must_use]
pub const fn iterations(&self) -> u32 {
self.iterations
}
#[inline(always)]
pub fn derive_secure(
self,
password: &PasswordString,
out_key: &mut Aes256Key32,
) -> Result<(), AescryptError> {
derive_pbkdf2_key(password, &self.salt, self.iterations, out_key)
}
#[inline(always)]
pub fn derive_secure_new(
self,
password: &PasswordString,
) -> Result<Aes256Key32, AescryptError> {
let mut key = Aes256Key32::new([0u8; 32]);
self.derive_secure(password, &mut key)?;
Ok(key)
}
}
impl Default for Pbkdf2Builder {
fn default() -> Self {
Self::new()
}
}