use std::convert::Infallible;
use std::fmt;
use nibkeep_base::Hash;
use rand_core::CryptoRng;
use zeroize::{Zeroize, ZeroizeOnDrop};
const KEY_HASHES_CONTEXT: &str = "nibkeep 2026-10 key hashes";
#[must_use]
pub fn key_hash(key: &Key) -> Hash {
Hash::of(key.derive(KEY_HASHES_CONTEXT).expose_bytes())
}
#[derive(Clone)]
pub struct Key([u8; 32]);
impl Key {
#[must_use]
pub fn generate(rng: &mut (impl CryptoRng + ?Sized)) -> Self {
let mut key = Self([0; 32]);
rng.fill_bytes(&mut key.0);
key
}
#[must_use]
pub const fn from_bytes(bytes: [u8; 32]) -> Self {
Self(bytes)
}
#[must_use]
pub fn from_slice(bytes: &[u8]) -> Option<Self> {
let bytes: &[u8; 32] = bytes.try_into().ok()?;
let Ok(key) = Self::fill_with(|key| {
key.copy_from_slice(bytes);
Ok::<(), Infallible>(())
});
Some(key)
}
#[must_use]
pub fn same_as(&self, other: &Self) -> bool {
blake3::Hash::from_bytes(self.0) == blake3::Hash::from_bytes(other.0)
}
#[must_use]
pub const fn expose_bytes(&self) -> &[u8; 32] {
&self.0
}
#[must_use]
pub fn derive(&self, context: &'static str) -> Self {
Self(blake3::derive_key(context, &self.0))
}
#[must_use]
pub fn tag(&self, message: &[u8]) -> [u8; 32] {
*blake3::keyed_hash(&self.0, message).as_bytes()
}
#[must_use]
pub fn verify_tag(&self, message: &[u8], tag: &[u8]) -> bool {
let Ok(tag) = <[u8; 32]>::try_from(tag) else {
return false;
};
blake3::keyed_hash(&self.0, message) == blake3::Hash::from_bytes(tag)
}
pub(crate) fn fill_with<E>(
fill: impl FnOnce(&mut [u8; 32]) -> Result<(), E>,
) -> Result<Self, E> {
let mut key = Self([0; 32]);
fill(&mut key.0)?;
Ok(key)
}
}
impl Drop for Key {
fn drop(&mut self) {
self.0.zeroize();
}
}
impl ZeroizeOnDrop for Key {}
impl fmt::Debug for Key {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Key(..)")
}
}