use crate::crypto::{DerivedKey, SALT_LEN};
use crate::error::Result;
use crate::format;
use std::path::Path;
use std::sync::Arc;
use zeroize::Zeroizing;
pub trait KeySource: Send + Sync {
fn key_for(&self, salt: &[u8; SALT_LEN]) -> Result<DerivedKey>;
fn fresh(&self, opened_with: &[u8; SALT_LEN]) -> Result<FreshKey>;
}
impl<T: KeySource + ?Sized> KeySource for Arc<T> {
fn key_for(&self, salt: &[u8; SALT_LEN]) -> Result<DerivedKey> {
(**self).key_for(salt)
}
fn fresh(&self, opened_with: &[u8; SALT_LEN]) -> Result<FreshKey> {
(**self).fresh(opened_with)
}
}
pub struct FreshKey {
pub salt: [u8; SALT_LEN],
pub key: DerivedKey,
pub proof: DerivedKey,
}
#[derive(Clone, Copy)]
pub enum Opener<'a> {
Password(&'a [u8]),
Source(&'a dyn KeySource),
}
impl Opener<'_> {
pub(crate) fn open(&self, sealed: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
match self {
Self::Password(password) => format::decode(password, sealed),
Self::Source(source) => {
let key = source.key_for(&format::salt_of(sealed)?)?;
format::open_under(&key, sealed)
}
}
}
pub fn opens(&self, path: &Path) -> bool {
std::fs::read(path)
.map(|sealed| self.open(&sealed).is_ok())
.unwrap_or(false)
}
}
impl<'a> From<&'a [u8]> for Opener<'a> {
fn from(password: &'a [u8]) -> Self {
Self::Password(password)
}
}
impl<'a, const N: usize> From<&'a [u8; N]> for Opener<'a> {
fn from(password: &'a [u8; N]) -> Self {
Self::Password(password)
}
}
impl<'a> From<&'a dyn KeySource> for Opener<'a> {
fn from(source: &'a dyn KeySource) -> Self {
Self::Source(source)
}
}