I have implemented HKDF in Rust, which passes all test vectors from RFC 5869, using HKDF with HMAC-SHA256. I also have a function to compare byte arrays in constant time, which I hope someone could confirm is correctly done. Any type of feedback is welcome.
EDIT: I mainly mean feedback on hkdf_compute(). HMAC in hkdf_extract() is defined in another module and not included here.
HKDF
pub struct Hkdf {
pub salt: Vec<u8>,
pub data: Vec<u8>,
pub info: Vec<u8>,
pub hmac: usize,
pub length: usize,
}
impl Drop for Hkdf {
fn drop(&mut self) {
//println!("DROPPING");
self.salt.clear();
self.data.clear();
self.info.clear()
}
}
impl Hkdf {
/// Return HMAC matching argument passsed to Hkdf.
pub fn hkdf_extract(&self, data: &[u8], salt: &[u8]) -> Vec<u8> {
let hmac_res = Hmac {
secret_key: salt.to_vec(),
message: data.to_vec(),
sha2: self.hmac
};
hmac_res.hmac_compute()
}
/// The HKDF Expand step. Returns an HKDF.
pub fn hkdf_compute(&self) -> Vec<u8> {
// Check that the selected key length is within the limit.
if self.length as f32 > 255_f32 * (self.hmac / 8) as f32 {
panic!("Derived key length above max. 255 * (HMAC OUTPUT LENGTH IN BYTES)");
}
let n_iter = (self.length as f32 / (self.hmac / 8) as f32).ceil() as usize;
let mut con_step: Vec<u8> = vec![];
let mut t_step: Vec<u8> = vec![];
let mut hkdf_final: Vec<u8> = vec![];
for x in 1..n_iter+1 {
con_step.append(&mut t_step);
con_step.extend_from_slice(&self.info);
con_step.push(x as u8);
t_step.extend_from_slice(&self.hkdf_extract(
&con_step,
&self.hkdf_extract(&self.data, &self.salt))
);
con_step.clear();
hkdf_final.extend_from_slice(&t_step);
}
hkdf_final.truncate(self.length);
hkdf_final
}
}
Compare constant time:
#[inline(never)]
/// Comparison in constant time.
pub fn compare_ct(x: &[u8], y: &[u8]) -> bool {
let length = x.len();
if length != y.len() {
false;
}
let mut result: u8 = 0;
for n in 0..length {
result |= x[n] ^ y[n];
}
result == 0
}
let hmac_res = Hmac { … }
, you useHmac
, which is unknown to us, the readers and reviewers. I guess you're more interested in a review ofhkdf_compute
only? \$\endgroup\$