pub mod argon2;
use std::fmt;
use std::error::Error;
use seckey::Bytes;
pub use self::argon2::Argon2i;
#[derive(Clone, Debug)]
pub enum KeyDerivationFail {
ParameterError(String),
OutLenTooShort,
OutLenTooLong,
SaltTooShort,
SaltTooLong
}
pub trait KeyDerive: Default {
fn with_size(&mut self, len: usize) -> &mut Self;
fn with_key(&mut self, key: &[u8]) -> &mut Self;
fn with_aad(&mut self, aad: &[u8]) -> &mut Self;
fn with_opslimit(&mut self, opslimit: u32) -> &mut Self;
fn with_memlimit(&mut self, memlimit: u32) -> &mut Self;
fn derive<K>(&self, password: &[u8], salt: &[u8])
-> Result<K, KeyDerivationFail>
where K: From<Vec<u8>>;
}
pub trait KeyVerify: KeyDerive {
fn verify(&self, password: &[u8], salt: &[u8], hash: &[u8]) -> Result<bool, KeyDerivationFail> {
Ok(self.derive::<Bytes>(password, salt)? == hash)
}
}
impl<T> KeyVerify for T where T: KeyDerive {}
impl fmt::Display for KeyDerivationFail {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Key Derivation fail: {}", self.description())
}
}
impl Error for KeyDerivationFail {
fn description(&self) -> &str {
match *self {
KeyDerivationFail::ParameterError(ref string) => string,
KeyDerivationFail::OutLenTooShort => "Output length too short.",
KeyDerivationFail::OutLenTooLong => "Output length too long.",
KeyDerivationFail::SaltTooShort => "Salt too short.",
KeyDerivationFail::SaltTooLong => "Salt too long."
}
}
}