forked from Argyle-Software/kyber
-
Notifications
You must be signed in to change notification settings - Fork 1
/
kat.rs
78 lines (71 loc) · 2.29 KB
/
kat.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#![cfg(feature = "KAT")]
mod load;
use load::*;
use pqc_kyber::*;
// Generate KAT keypairs from seeds.
#[test]
fn keypairs() {
let kats = build_kats();
let mut _rng = rand::thread_rng(); // placeholder
for kat in kats {
let known_pk = decode_hex(&kat.pk);
let known_sk = decode_hex(&kat.sk);
let buf1 = decode_hex(&kat.keygen_buffer1);
let buf2 = decode_hex(&kat.keygen_buffer2);
let bufs = Some((&buf1[..], &buf2[..]));
let mut pk = [0u8; KYBER_PUBLICKEYBYTES];
let mut sk = [0u8; KYBER_SECRETKEYBYTES];
crypto_kem_keypair(&mut pk, &mut sk, &mut _rng, bufs);
assert_eq!(&pk[..], &known_pk[..], "Public key KAT mismatch");
assert_eq!(&sk[..], &known_sk[..], "Secret key KAT mismatch");
}
}
// Encapsulating KAT's using deterministic rand buffers
#[test]
fn encaps() {
let kats = build_kats();
let mut _rng = rand::thread_rng(); // placeholder
for kat in kats {
let known_ss = decode_hex(&kat.ss);
let pk = decode_hex(&kat.pk);
let buf1 = decode_hex(&kat.encap_buffer);
let encap_buf = Some(&buf1[..]);
let mut ct = [0u8; KYBER_CIPHERTEXTBYTES];
let mut ss = [0u8; KYBER_SSBYTES];
crypto_kem_enc(&mut ct, &mut ss, &pk, &mut _rng, encap_buf);
assert_eq!(&ss[..], &known_ss[..], "Shared secret KAT mismatch");
}
}
// Decapsulating KAT's
#[test]
fn decaps() {
let kats = build_kats();
for kat in kats {
let sk = decode_hex(&kat.sk);
let ct = decode_hex(&kat.ct);
let known_ss = decode_hex(&kat.ss);
let decap_result = decapsulate(&ct, &sk);
assert!(decap_result.is_ok(), "KEM decapsulation failure");
assert_eq!(
&decap_result.unwrap()[..],
&known_ss[..],
"Shared secret KAT doesn't match"
)
}
}
// Helper functions
// Encodes byte slice into a hex string
pub fn encode_hex(bytes: &[u8]) -> String {
let mut output = String::new();
for b in bytes {
output.push_str(&format!("{:02X}", b));
}
output
}
// Decodes hex string into a vector of bytes
pub fn decode_hex(s: &str) -> Vec<u8> {
(0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("Hex string decoding"))
.collect::<Vec<u8>>()
}