use sha1::Sha1;
use sha2::{Digest, Sha256};
use crate::error::{Error, Result};
#[derive(Debug, Clone, Copy)]
pub enum Hash {
Sha1,
Sha256,
}
impl Hash {
fn digest_len(self) -> usize {
match self {
Hash::Sha1 => 20,
Hash::Sha256 => 32,
}
}
fn hash(self, data: &[u8]) -> Vec<u8> {
match self {
Hash::Sha1 => {
let mut h = Sha1::new();
h.update(data);
h.finalize().to_vec()
}
Hash::Sha256 => {
let mut h = Sha256::new();
h.update(data);
h.finalize().to_vec()
}
}
}
}
pub fn octet_string_to_key(
hash: Hash,
zz: &[u8],
other_info: &[u8],
key_bytes: usize,
) -> Result<Vec<u8>> {
if key_bytes == 0 {
return Err(Error::Kdf("key_bytes = 0".into()));
}
let dlen = hash.digest_len();
let reps = (key_bytes + dlen - 1) / dlen;
if reps > 0xFFFF_FFFF {
return Err(Error::Kdf("too much output requested".into()));
}
let mut out = Vec::with_capacity(reps * dlen);
for i in 1..=reps as u32 {
let mut buf = Vec::with_capacity(4 + zz.len() + other_info.len());
buf.extend_from_slice(&i.to_be_bytes());
buf.extend_from_slice(zz);
buf.extend_from_slice(other_info);
out.extend_from_slice(&hash.hash(&buf));
}
out.truncate(key_bytes);
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deterministic_and_length_correct() {
let k1 = octet_string_to_key(Hash::Sha256, b"ZZ", b"info", 32).unwrap();
let k2 = octet_string_to_key(Hash::Sha256, b"ZZ", b"info", 32).unwrap();
assert_eq!(k1, k2);
assert_eq!(k1.len(), 32);
let long = octet_string_to_key(Hash::Sha256, b"ZZ", b"info", 64).unwrap();
assert_eq!(&long[..32], k1.as_slice());
assert_ne!(&long[32..], k1.as_slice());
}
}