use argon2::{Algorithm, Argon2, Version};
use attrkey::{Attributes, Keyspace};
use chacha20::ChaCha20Rng;
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use subtle::{Choice, ConstantTimeEq};
use zeroize::Zeroize;
use crate::attributes::AttributeKind;
use crate::errors::HkErr;
use crate::params::Params;
pub const CROCKFORD_BASE32: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
pub struct Profile<K> {
inner: BTreeMap<K, Vec<u8>>,
}
impl<K: AttributeKind> Profile<K> {
pub fn new() -> Self {
Self {
inner: BTreeMap::new(),
}
}
pub fn insert(&mut self, kind: K, value: impl Into<Vec<u8>>) {
self.inner.insert(kind, value.into());
}
pub fn harden(mut self, params: &Params) -> Result<Fingerprint<K>, HkErr> {
let order: Vec<K> = self.inner.keys().copied().collect();
let values: Vec<Vec<u8>> =
std::mem::take(&mut self.inner).into_values().collect();
let argon2_params = argon2::Params::new(
params.m_cost,
params.t_cost,
params.p_cost,
None,
)?;
let hasher =
Argon2::new(Algorithm::Argon2id, Version::V0x13, argon2_params);
let collection = Attributes::<_, ChaCha20Rng>::new(values, hasher)?;
let keyspace =
collection.harden(params.constraint, params.context.as_deref())?;
Ok(Fingerprint {
keyspace,
order,
chars: params.chars,
})
}
}
impl<K> Drop for Profile<K> {
fn drop(&mut self) {
for value in self.inner.values_mut() {
value.zeroize();
}
}
}
impl<K: AttributeKind> Extend<(K, Vec<u8>)> for Profile<K> {
fn extend<T: IntoIterator<Item = (K, Vec<u8>)>>(&mut self, iter: T) {
self.inner.extend(iter);
}
}
impl<K: AttributeKind> FromIterator<(K, Vec<u8>)> for Profile<K> {
fn from_iter<T: IntoIterator<Item = (K, Vec<u8>)>>(iter: T) -> Self {
Self {
inner: BTreeMap::from_iter(iter),
}
}
}
pub struct Fingerprint<K> {
keyspace: Keyspace<ChaCha20Rng>,
order: Vec<K>,
chars: u8,
}
impl<K: AttributeKind> Fingerprint<K> {
pub fn confirm(&self, selection: &[K]) -> Result<Confirmation<K>, HkErr> {
let indices = self.resolve(selection)?;
let (key, _) = self.keyspace.extract_pair(&indices)?;
let mut key_bytes = key.to_bytes();
let digest = Sha256::digest(key_bytes);
let code = digest
.iter()
.take(self.chars as usize)
.map(|b| CROCKFORD_BASE32[(b % 32) as usize] as char)
.collect();
key_bytes.zeroize();
Ok(Confirmation {
code,
selection: selection.to_vec(),
})
}
pub fn derive_key(
&self,
confirmation: &Confirmation<K>,
output_len: Option<usize>,
) -> Result<Vec<u8>, HkErr> {
let indices = self.verify(confirmation)?;
Ok(self.keyspace.derive_key(&indices, output_len)?)
}
#[cfg(feature = "unchecked")]
pub fn derive_key_unchecked(
&self,
selection: &[K],
output_len: Option<usize>,
) -> Result<Vec<u8>, HkErr> {
let indices = self.resolve(selection)?;
Ok(self.keyspace.derive_key(&indices, output_len)?)
}
pub fn derive_key_into(
&self,
confirmation: &Confirmation<K>,
dst: &mut [u8],
) -> Result<(), HkErr> {
let indices = self.verify(confirmation)?;
Ok(self.keyspace.derive_key_into(&indices, dst)?)
}
#[cfg(feature = "unchecked")]
pub fn derive_key_into_unchecked(
&self,
selection: &[K],
dst: &mut [u8],
) -> Result<(), HkErr> {
let indices = self.resolve(selection)?;
Ok(self.keyspace.derive_key_into(&indices, dst)?)
}
fn resolve(&self, kinds: &[K]) -> Result<Vec<usize>, HkErr> {
kinds
.iter()
.map(|kind| {
self.order
.binary_search(kind)
.map_err(|_| HkErr::AttributeNotFound(format!("{kind:?}")))
})
.collect()
}
fn verify(
&self,
confirmation: &Confirmation<K>,
) -> Result<Vec<usize>, HkErr> {
let mut expected = self.confirm(&confirmation.selection)?;
if expected.ct_ne(confirmation).into() {
return Err(HkErr::BadConfirmation);
}
expected.zeroize();
self.resolve(&confirmation.selection)
}
}
#[derive(Debug, PartialEq, Eq, Zeroize)]
pub struct Confirmation<K> {
code: String,
#[zeroize(skip)]
selection: Vec<K>,
}
impl<K: AttributeKind> Confirmation<K> {
pub fn code(&self) -> &str {
&self.code
}
pub fn selection(&self) -> &[K] {
&self.selection
}
}
impl<K: AttributeKind> ConstantTimeEq for Confirmation<K> {
fn ct_eq(&self, other: &Self) -> Choice {
let code_eq = self.code.as_bytes().ct_eq(other.code.as_bytes());
let selection_eq =
Choice::from((self.selection == other.selection) as u8);
code_eq & selection_eq
}
}
#[cfg(test)]
mod tests {
use super::*;
use attrkey::AttrkeyError;
use crate::attributes::Attribute;
use crate::params::Params;
fn get_params() -> Params {
Params::new(1024, 1, 1, 8, None, None).expect("valid params")
}
fn make_profile() -> Profile<Attribute> {
let mut profile = Profile::new();
profile.insert(Attribute::Name, b"MUSTERMANN");
profile.insert(Attribute::GivenName, b"ERIKA");
profile.insert(Attribute::BirthName, b"GABLER");
profile.insert(Attribute::DateOfBirth, b"12.08.1964");
profile.insert(Attribute::Nationality, b"DEUTSCH");
profile.insert(Attribute::CityOfBirth, b"BERLIN");
profile.insert(Attribute::EyeColor, b"GREEN");
profile.insert(Attribute::Height, b"160CM");
profile
}
fn make_fingerprint() -> Fingerprint<Attribute> {
let params = get_params();
make_profile()
.harden(¶ms)
.expect("hardening should produce a fingerprint")
}
#[test]
fn drop_zeroizes_remaining_values() {
let mut profile = Profile::new();
profile.insert(Attribute::Name, b"MUSTERMANN");
profile.insert(Attribute::GivenName, b"ERIKA");
profile.insert(Attribute::DateOfBirth, b"12.08.1964");
drop(profile);
}
#[test]
fn extend_adds_attributes() {
let mut profile = Profile::new();
profile.insert(Attribute::Name, b"MUSTERMANN");
profile.extend([
(Attribute::GivenName, b"ERIKA".to_vec()),
(Attribute::DateOfBirth, b"12.08.1964".to_vec()),
]);
assert_eq!(profile.inner.len(), 3);
}
#[test]
fn collects_into_profile_from_iterator() {
let data = [
(Attribute::Name, b"MUSTERMANN".to_vec()),
(Attribute::GivenName, b"ERIKA".to_vec()),
(Attribute::DateOfBirth, b"12.08.1964".to_vec()),
];
let profile: Profile<Attribute> = data.into_iter().collect();
assert_eq!(profile.inner.len(), 3);
}
#[test]
fn harden_produces_fingerprint() {
let params = get_params();
let result = make_profile().harden(¶ms);
assert!(result.is_ok())
}
#[test]
fn harden_fails_empty_profile() {
let empty: Profile<Attribute> = Profile::new();
let params = get_params();
let result = empty.harden(¶ms);
assert!(matches!(
result,
Err(HkErr::Attrkey(AttrkeyError::AttributesTooFew))
))
}
#[test]
fn confirm_produces_confirmation() {
let fingerprint = make_fingerprint();
let selection = [Attribute::Name, Attribute::EyeColor];
let result = fingerprint.confirm(&selection);
assert!(result.is_ok());
let confirmation = result.unwrap();
assert!(!confirmation.code().is_empty());
assert!(
confirmation
.code()
.bytes()
.all(|b| CROCKFORD_BASE32.contains(&b))
);
assert_eq!(confirmation.selection(), selection.as_slice());
}
#[test]
fn confirm_fails_empty_selection() {
let fingerprint = make_fingerprint();
let result = fingerprint.confirm(&[]);
assert!(matches!(
result,
Err(HkErr::Attrkey(AttrkeyError::IndicesTooFew))
));
}
#[test]
fn confirm_fails_attribute_not_found() {
let fingerprint = make_fingerprint();
let selection = [Attribute::Employer];
let result = fingerprint.confirm(&selection);
let expected = format!("{:?}", Attribute::Employer);
assert_eq!(result, Err(HkErr::AttributeNotFound(expected)))
}
#[test]
fn confirm_fails_selecting_all_attributes() {
let fingerprint = make_fingerprint();
let selection = [
Attribute::Name,
Attribute::GivenName,
Attribute::BirthName,
Attribute::DateOfBirth,
Attribute::Nationality,
Attribute::CityOfBirth,
Attribute::EyeColor,
Attribute::Height,
];
let result = fingerprint.confirm(&selection);
assert!(matches!(
result,
Err(HkErr::Attrkey(AttrkeyError::IndicesTooMany))
));
}
#[test]
fn derive_key_produces_key() {
let fingerprint = make_fingerprint();
let selection = [Attribute::Name, Attribute::EyeColor];
let result = fingerprint.confirm(&selection);
assert!(result.is_ok());
let confirmation = result.unwrap();
let result = fingerprint.derive_key(&confirmation, None);
assert!(result.is_ok());
assert_eq!(result.unwrap().len(), 32);
}
#[test]
fn derive_key_with_output_len_produces_key() {
let fingerprint = make_fingerprint();
let selection = [Attribute::Name, Attribute::EyeColor];
let result = fingerprint.confirm(&selection);
assert!(result.is_ok());
let confirmation = result.unwrap();
let result = fingerprint.derive_key(&confirmation, Some(48));
assert!(result.is_ok());
assert_eq!(result.unwrap().len(), 48);
}
#[test]
fn derive_key_fails_bad_confirmation_tampered_code() {
let fingerprint = make_fingerprint();
let selection = [Attribute::Name, Attribute::EyeColor];
let result = fingerprint.confirm(&selection);
assert!(result.is_ok());
let mut confirmation = result.unwrap();
confirmation.code = "ZZZZZZ".to_string();
let result = fingerprint.derive_key(&confirmation, None);
assert_eq!(result, Err(HkErr::BadConfirmation));
}
#[test]
fn derive_key_fails_bad_confirmation_tampered_selection() {
let fingerprint = make_fingerprint();
let selection = [Attribute::Name, Attribute::EyeColor];
let result = fingerprint.confirm(&selection);
assert!(result.is_ok());
let mut confirmation = result.unwrap();
confirmation.selection =
vec![Attribute::DateOfBirth, Attribute::Nationality];
let result = fingerprint.derive_key(&confirmation, None);
assert_eq!(result, Err(HkErr::BadConfirmation));
}
#[cfg(feature = "unchecked")]
#[test]
fn derive_key_unchecked_produces_key() {
let fingerprint = make_fingerprint();
let selection = [Attribute::Name, Attribute::EyeColor];
let result = fingerprint.derive_key_unchecked(&selection, None);
assert!(result.is_ok());
assert_eq!(result.unwrap().len(), 32);
}
#[cfg(feature = "unchecked")]
#[test]
fn derive_key_unchecked_fails_attribute_not_found() {
let fingerprint = make_fingerprint();
let selection = [Attribute::Employer];
let result = fingerprint.derive_key_unchecked(&selection, None);
let expected = format!("{:?}", Attribute::Employer);
assert_eq!(result, Err(HkErr::AttributeNotFound(expected)))
}
#[cfg(feature = "unchecked")]
#[test]
fn derive_key_unchecked_fails_empty_selection() {
let fingerprint = make_fingerprint();
let result = fingerprint.derive_key_unchecked(&[], None);
assert_eq!(result, Err(HkErr::Attrkey(AttrkeyError::IndicesTooFew)));
}
#[cfg(feature = "unchecked")]
#[test]
fn derive_key_unchecked_fails_selecting_all_attributes() {
let fingerprint = make_fingerprint();
let selection = [
Attribute::Name,
Attribute::GivenName,
Attribute::BirthName,
Attribute::DateOfBirth,
Attribute::Nationality,
Attribute::CityOfBirth,
Attribute::EyeColor,
Attribute::Height,
];
let result = fingerprint.derive_key_unchecked(&selection, None);
assert_eq!(result, Err(HkErr::Attrkey(AttrkeyError::IndicesTooMany)));
}
#[test]
fn derive_key_into_fills_buffer() {
let fingerprint = make_fingerprint();
let selection = [Attribute::Name, Attribute::EyeColor];
let mut dst = [0u8; 48];
let result = fingerprint.confirm(&selection);
assert!(result.is_ok());
let confirmation = result.unwrap();
let result = fingerprint.derive_key_into(&confirmation, &mut dst);
assert!(result.is_ok());
}
#[test]
fn derive_key_into_fails_bad_confirmation() {
let fingerprint = make_fingerprint();
let selection = [Attribute::Name, Attribute::EyeColor];
let mut dst = [0u8; 48];
let result = fingerprint.confirm(&selection);
assert!(result.is_ok());
let mut confirmation = result.unwrap();
confirmation.code = "ZZZZZZ".to_string();
let result = fingerprint.derive_key_into(&confirmation, &mut dst);
assert_eq!(result, Err(HkErr::BadConfirmation));
}
#[cfg(feature = "unchecked")]
#[test]
fn derive_key_into_unchecked_fills_buffer() {
let fingerprint = make_fingerprint();
let selection = [Attribute::Name, Attribute::EyeColor];
let mut dst = [0u8; 48];
let result =
fingerprint.derive_key_into_unchecked(&selection, &mut dst);
assert!(result.is_ok());
}
}