Skip to content

Commit 0b60b12

Browse files
author
Ahmed
committed
ntru: Add core streamlined NTRU implementation
Signed-off-by: Ahmed <>
1 parent c6f7b41 commit 0b60b12

3 files changed

Lines changed: 54 additions & 1 deletion

File tree

ntru/src/core/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pub mod streamlined;

ntru/src/core/streamlined.rs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
use hybrid_array::typenum::Unsigned;
2+
use rand_core::CryptoRngCore;
3+
4+
use crate::{
5+
algebra::{f3::Small, r3::R3, rq::Rq},
6+
params::NtruCommon,
7+
};
8+
9+
/// (h,f,ginv) = `key_gen()`
10+
pub fn key_gen<Params: NtruCommon>(
11+
rng: &mut impl CryptoRngCore,
12+
) -> (Rq<Params>, R3<Params>, R3<Params>) {
13+
let mut g = R3::default();
14+
let mut ginv = R3::default();
15+
loop {
16+
g.small_random_buffer(rng);
17+
if g.recip_buffer(&mut ginv) == 0 {
18+
break;
19+
};
20+
}
21+
let f = R3::short_random(rng);
22+
let (finv, status) = Rq::recip3(&f);
23+
debug_assert_eq!(status, 0);
24+
let h = finv.mult_r3(&g);
25+
(h, f, ginv)
26+
}
27+
28+
pub fn encrypt<Params: NtruCommon>(r: &R3<Params>, h: &Rq<Params>) -> Rq<Params> {
29+
let hr = h.mult_r3(r);
30+
hr.round()
31+
}
32+
33+
pub fn decrypt<Params: NtruCommon>(
34+
c: &Rq<Params>,
35+
f: &R3<Params>,
36+
ginv: &R3<Params>,
37+
) -> R3<Params> {
38+
let cf = c.mult_r3(f);
39+
let cf3 = cf.mult3();
40+
let e: R3<Params> = cf3.into();
41+
let ev = e.mult(ginv);
42+
let mask = ev.weight_w_mask() as i8;
43+
let mut r = R3::<Params>::default();
44+
for i in 0..Params::W as usize {
45+
r.0[i] = Small::new_i8(((*ev.0[i] ^ 1) & !mask) ^ 1);
46+
}
47+
for i in Params::W as usize..Params::P::USIZE {
48+
r.0[i] = Small::new_i8(*ev.0[i] & !mask);
49+
}
50+
r
51+
}

ntru/src/lib.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@
1717
clippy::similar_names,
1818
)]
1919

20+
mod algebra;
2021
pub mod const_time;
21-
pub mod algebra;
22+
pub mod core;
2223
pub mod params;
2324

2425
use hybrid_array::sizes::{U1013, U1277, U653, U761, U857, U953};

0 commit comments

Comments
 (0)