coffio/src/kdf.rs
2024-04-20 19:02:55 +02:00

98 lines
2.8 KiB
Rust

use crate::canonicalization::canonicalize;
use crate::context::KeyContext;
use crate::ikm::InputKeyMaterial;
pub(crate) type KdfFunction = dyn Fn(&str, &[u8]) -> Vec<u8>;
pub(crate) fn derive_key(
ikm: &InputKeyMaterial,
ctx: &KeyContext,
time_period: Option<u64>,
) -> Vec<u8> {
let mut elems = ctx.get_ctx_elems(time_period);
elems.push(ikm.scheme.get_key_len().to_le_bytes().to_vec());
let key_context = canonicalize(&elems);
let kdf = ikm.scheme.get_kdf();
kdf(&key_context, &ikm.content)
}
#[cfg(test)]
mod tests {
use crate::ikm::InputKeyMaterial;
use crate::KeyContext;
use std::num::NonZeroU64;
const TEST_RAW_IKM: &[u8] = &[
0x0a, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x7b, 0x85, 0x27, 0xef, 0xf2, 0xbd, 0x58,
0x9f, 0x6e, 0xb1, 0x7b, 0x71, 0xc3, 0x1e, 0xf6, 0xfd, 0x7f, 0x90, 0xdb, 0xc6, 0x43, 0xea,
0xe9, 0x9c, 0xa3, 0xb5, 0xee, 0xcc, 0xb6, 0xb6, 0x28, 0x6a, 0xbd, 0xe4, 0xd0, 0x65, 0x00,
0x00, 0x00, 0x00, 0x3d, 0x82, 0x6f, 0x8b, 0x00, 0x00, 0x00, 0x00, 0x00,
];
#[test]
#[cfg(feature = "chacha")]
fn derive_key_no_tp() {
let ikm = InputKeyMaterial::from_bytes(TEST_RAW_IKM).unwrap();
let ctx = KeyContext::from(["some", "context"]);
assert_eq!(
super::derive_key(&ikm, &ctx, None),
vec![
0xf9, 0x90, 0x22, 0x8, 0x9a, 0x63, 0x2, 0xc9, 0xd0, 0x7c, 0x71, 0x56, 0xa4, 0xc3,
0x8c, 0x4b, 0x1d, 0xe8, 0x56, 0xf2, 0xc3, 0xf6, 0xba, 0xc3, 0x4b, 0x8d, 0x85, 0x29,
0x4b, 0x5, 0x13, 0xc3
]
);
}
#[test]
#[cfg(feature = "chacha")]
fn derive_key_tp_0() {
let ikm = InputKeyMaterial::from_bytes(TEST_RAW_IKM).unwrap();
let ctx = KeyContext::from(["some", "context"]);
assert_eq!(
super::derive_key(&ikm, &ctx, Some(0)),
vec![
0xfe, 0x70, 0x65, 0x84, 0x79, 0x9a, 0xc0, 0xf1, 0x50, 0xb5, 0x72, 0x73, 0x16, 0xf4,
0x5b, 0x49, 0xb4, 0x46, 0xfa, 0x58, 0xa6, 0xb9, 0xf0, 0xc7, 0xec, 0x49, 0x87, 0x7e,
0x46, 0xd0, 0x9, 0xe8
]
);
}
#[test]
#[cfg(feature = "chacha")]
fn derive_key_tp_42() {
let ikm = InputKeyMaterial::from_bytes(TEST_RAW_IKM).unwrap();
let ctx = KeyContext::from(["some", "context"]);
assert_eq!(
super::derive_key(&ikm, &ctx, Some(42)),
vec![
0x5c, 0x9b, 0x1c, 0xfa, 0x21, 0xac, 0xdb, 0x37, 0x4d, 0xee, 0x60, 0xf7, 0x6, 0x18,
0x85, 0xb5, 0x95, 0x2a, 0x6c, 0xd3, 0x43, 0x9, 0xcb, 0x1b, 0x7f, 0x9d, 0xdf, 0x58,
0xf9, 0x3e, 0x6e, 0x14
]
);
}
#[test]
fn get_time_period() {
let test_vec = &[
// (periodicity, timestamp, reference value)
(1, 0, 0),
(1, 1, 1),
(1, 2, 2),
(1, 35015, 35015),
(16_777_216, 0, 0),
(16_777_216, 16_777_215, 0),
(16_777_216, 16_777_216, 1),
(16_777_216, 1_709_994_382, 101),
];
let mut ctx = KeyContext::from([]);
for (p, ts, ref_val) in test_vec {
let p = NonZeroU64::new(*p).unwrap();
ctx.set_periodicity(p);
let tp = ctx.get_time_period(*ts);
assert_eq!(tp, Some(*ref_val));
}
}
}