2023-02-17 13:59:02 +00:00
|
|
|
//! Hash-based Key Derivation Function
|
|
|
|
//! We just repackage other crates
|
|
|
|
|
|
|
|
use ::hkdf::Hkdf;
|
|
|
|
use ::sha3::Sha3_256;
|
|
|
|
use ::zeroize::Zeroize;
|
|
|
|
|
|
|
|
use crate::enc::sym::Secret;
|
|
|
|
|
|
|
|
// Hack & tricks:
|
2023-02-17 22:09:49 +00:00
|
|
|
// HKDF are pretty important, but this lib don't zero out the data.
|
|
|
|
// we can't use #[derive(Zeroing)] either.
|
|
|
|
// So we craete a union with a Zeroing object, and drop both manually.
|
2023-02-17 13:59:02 +00:00
|
|
|
|
|
|
|
#[derive(Zeroize)]
|
|
|
|
#[zeroize(drop)]
|
|
|
|
struct Zeroable([u8; ::core::mem::size_of::<Hkdf<Sha3_256>>()]);
|
|
|
|
|
|
|
|
union HkdfInner {
|
|
|
|
hkdf: ::core::mem::ManuallyDrop<Hkdf<Sha3_256>>,
|
|
|
|
zeroable: ::core::mem::ManuallyDrop<Zeroable>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for HkdfInner {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
#[allow(unsafe_code)]
|
|
|
|
unsafe {
|
|
|
|
drop(&mut self.hkdf);
|
|
|
|
drop(&mut self.zeroable);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Sha3 based HKDF
|
|
|
|
#[allow(missing_debug_implementations)]
|
|
|
|
pub struct HkdfSha3 {
|
2023-02-17 22:09:49 +00:00
|
|
|
inner: HkdfInner,
|
2023-02-17 13:59:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl HkdfSha3 {
|
|
|
|
/// Instantiate a new HKDF with Sha3-256
|
2023-02-17 22:09:49 +00:00
|
|
|
pub fn new(salt: &[u8], key: Secret) -> Self {
|
|
|
|
let hkdf = Hkdf::<Sha3_256>::new(Some(salt), key.as_ref());
|
|
|
|
#[allow(unsafe_code)]
|
|
|
|
unsafe {
|
|
|
|
Self {
|
|
|
|
inner: HkdfInner {
|
|
|
|
hkdf: ::core::mem::ManuallyDrop::new(hkdf),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
/// Get a secret generated from the key and a given context
|
|
|
|
pub fn get_secret(&self, context: &[u8]) -> Secret {
|
|
|
|
let mut out: [u8; 32] = [0; 32];
|
|
|
|
#[allow(unsafe_code)]
|
|
|
|
unsafe {
|
|
|
|
self.inner.hkdf.expand(context, &mut out);
|
2023-02-17 13:59:02 +00:00
|
|
|
}
|
2023-02-17 22:09:49 +00:00
|
|
|
out.into()
|
2023-02-17 13:59:02 +00:00
|
|
|
}
|
|
|
|
}
|