use super::*;
const CAVP_TLS_CASES: usize = 40;
const CAVP_TLS_CASES_RUN: usize = 20;
#[test]
fn the_tls_1_2_prf_matches_the_nist_cavp_tls_kdf_vectors() -> Result<()> {
let provider = crypto::default_provider().unwrap();
let crypto = provider.crypto();
let hex = |s: &str| -> Vec<u8> {
(0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("hex"))
.collect()
};
let mut hash: Option<CipherSuiteHash> = None;
let mut key_block_bits = 0usize;
let mut fields: Vec<(String, Vec<u8>)> = Vec::new();
let (mut cases, mut run) = (0usize, 0usize);
let mut check = |hash: Option<CipherSuiteHash>,
key_block_bits: usize,
fields: &mut Vec<(String, Vec<u8>)>|
-> Result<()> {
if fields.is_empty() {
return Ok(());
}
cases += 1;
let get = |key: &str| -> &[u8] {
&fields
.iter()
.find(|(k, _)| k == key)
.unwrap_or_else(|| panic!("missing {key}"))
.1
};
if let Some(h) = hash {
let master = prf_master_secret(
crypto,
get("pre_master_secret"),
get("clientHello_random"),
get("serverHello_random"),
h,
)?;
assert_eq!(master.as_ref(), get("master_secret"), "case {cases}");
assert_eq!(key_block_bits % 64, 0);
let length = key_block_bits / 8;
let keys = prf_encryption_keys(
crypto,
master.as_ref(),
get("client_random"),
get("server_random"),
EncryptionKeyLengths {
mac: length / 4,
key: length / 8,
iv: length / 8,
},
h,
)?;
let block = [
keys.client_mac_key.as_slice(),
&keys.server_mac_key,
&keys.client_write_key,
&keys.server_write_key,
&keys.client_write_iv,
&keys.server_write_iv,
]
.concat();
assert_eq!(block, get("key_block"), "case {cases}");
run += 1;
}
fields.clear();
Ok(())
};
for line in include_str!("testdata/nist_cavp_tls_kdf.rsp").lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
if let Some(section) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
check(hash, key_block_bits, &mut fields)?;
if let Some(bits) = section.strip_prefix("key block length = ") {
key_block_bits = bits.parse().expect("a length");
} else if section.starts_with("TLS") {
hash = match section {
"TLS 1.2, SHA-256" => Some(CipherSuiteHash::Sha256),
"TLS 1.2, SHA-384" => Some(CipherSuiteHash::Sha384),
"TLS 1.0/1.1" | "TLS 1.2, SHA-512" => None,
other => panic!("unknown section {other}"),
};
}
continue;
}
let (key, value) = line.split_once(" = ").expect("key = value");
if key == "COUNT" {
check(hash, key_block_bits, &mut fields)?;
continue;
}
fields.push((key.to_owned(), hex(value)));
}
check(hash, key_block_bits, &mut fields)?;
assert_eq!((cases, run), (CAVP_TLS_CASES, CAVP_TLS_CASES_RUN));
Ok(())
}