pub const DEFAULT_COST: u32 = 12;
pub use crate::error::{RcryptError, RcryptResult};
mod algorithms;
pub fn hash<T: AsRef<[u8]>>(password: T, cost: u32) -> RcryptResult<Vec<u8>> {
let hash = crate::algorithms::rcrypt_hash(password.as_ref(), cost)?;
Ok(hash)
}
pub fn hash_with_salt<T: AsRef<[u8]>>(
password: T,
cost: u32,
salt: &[u8],
) -> RcryptResult<Vec<u8>> {
let hash = crate::algorithms::rcrypt_hash_with(password.as_ref(), cost, salt)?;
Ok(hash)
}
pub fn verify<T: AsRef<[u8]>>(password: T, hash: &[u8]) -> RcryptResult<bool> {
let verified = crate::algorithms::rcrypt_verify(password.as_ref(), hash)?;
Ok(verified)
}
pub mod bmcf {
pub use crate::algorithms::decode_into_mcf;
pub use crate::algorithms::encode_into_bmcf;
}
mod error {
use std::fmt;
pub type RcryptResult<T> = Result<T, RcryptError>;
#[derive(Debug)]
pub enum RcryptError {
CorruptedHash(String),
WrongSize(usize, usize),
UnsupportedHashPrefix(u8),
BadDecodedCost(String),
DisallowedCost(u32),
UnknownScheme(String),
Base64Error(base64::DecodeError),
BadPassword,
RngError(getrandom::Error),
BadSalt(usize),
}
macro_rules! from {
($($ty:ty, $var:expr),*) => {
$(impl From<$ty> for RcryptError {
fn from(e: $ty) -> Self {
$var(e)
}
})*
};
}
from!(
base64::DecodeError,
RcryptError::Base64Error,
getrandom::Error,
RcryptError::RngError
);
impl fmt::Display for RcryptError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RcryptError::BadDecodedCost(c) => write!(f, "failed to decode cost: {}", c),
RcryptError::Base64Error(e) => write!(f, "base64 decode error: {}", e),
RcryptError::CorruptedHash(e) => write!(f, "corrupted hash: {}", e),
RcryptError::UnknownScheme(e) => write!(f, "unknown scheme: {}", e),
RcryptError::UnsupportedHashPrefix(p) => write!(f, "unsupported prefix: {}", p),
RcryptError::WrongSize(esz, sz) => {
write!(f, "wrong hash size. expected {} bytes, found {}", esz, sz)
}
RcryptError::BadPassword => write!(f, "Bad password"),
RcryptError::DisallowedCost(cst) => write!(f, "illegal cost: {}", cst),
RcryptError::RngError(e) => write!(f, "error while generating salt: {}", e),
RcryptError::BadSalt(slt) => write!(f, "Expected salt with 16 bytes. got {}", slt),
}
}
}
}