From f192f29a862c536c75876dad875b9366268527e5 Mon Sep 17 00:00:00 2001 From: Sam Hadow Date: Sat, 24 May 2025 00:30:39 +0200 Subject: [PATCH] integrate in agcd --- src/agcd.rs | 31 +++++++++++++++++++------------ src/deep_lll.rs | 12 +++++++++--- 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/src/agcd.rs b/src/agcd.rs index f655507..6a67977 100644 --- a/src/agcd.rs +++ b/src/agcd.rs @@ -1,29 +1,36 @@ use crate::bkz::bkz_reduce; +use crate::deep_lll::deep_lll; use crate::matrix::Matrix; use crate::utils::abs; use lll_rs::l2::bigl2; -use rug::Integer; +use rug::{Integer, Rational}; pub fn agcd(ciphertexts: Vec, noise_bits: usize, algorithm: u8) -> Integer { // 1. Build lattice matrix basis let basis_matrix = Matrix::new_lattice(noise_bits, ciphertexts.clone()).unwrap(); - // 2. reduce with LLL + // 2. reduce with LLL, and extract first element of shortest vector let mut lll_matrix = basis_matrix.to_lll_matrix(); println!("basis: {:?}", lll_matrix); - match algorithm { - 0u8 => bigl2::lattice_reduce(&mut lll_matrix, 0.51, 0.75), - 1u8 => bkz_reduce(&mut lll_matrix, 16, 0.75, 0.75, 10), - _ => panic!(), - } - println!("basis after reduction: {:?}", lll_matrix); - // 3. Extract shortest vector - let shortest_vector = &lll_matrix[0]; - println!("Shortest vector: {:?}", shortest_vector); + let first_elem = match algorithm { + 0u8 => { + bigl2::lattice_reduce(&mut lll_matrix, 0.51, 0.75); + lll_matrix[0][0].clone() + } + 1u8 => { + bkz_reduce(&mut lll_matrix, 16, 0.75, 0.75, 10); + lll_matrix[0][0].clone() + } + 2u8 => { + let reduced = deep_lll(basis_matrix.clone(), Rational::from((51, 100))).unwrap(); + reduced.columns[0][0].clone() + } + _ => panic!("Unknown algorithm value: {}", algorithm), + }; // 4. q0 candidate - let q0 = &shortest_vector[0] / (Integer::from(1) << (noise_bits + 1)); + let q0 = first_elem / (Integer::from(1) << (noise_bits + 1)); println!("q0: {}", q0); if q0 == 0 { diff --git a/src/deep_lll.rs b/src/deep_lll.rs index 3a6da05..e85a14b 100644 --- a/src/deep_lll.rs +++ b/src/deep_lll.rs @@ -1,5 +1,5 @@ use crate::matrix::Matrix; -use rug::{Integer, Rational}; +use rug::Rational; /// Perform DeepLLL reduction on a given lattice basis represented by Matrix. /// 1/4 < delta < 1. @@ -7,11 +7,19 @@ pub fn deep_lll(mut mat: Matrix, delta: Rational) -> Option { let n = mat.n; let (mut mu, mut b_star_sq) = gramm_schmidt(&mat); let mut k = 2; + let mut iterations = 0; + const MAX_ITERATIONS: usize = 100; while k <= n { + if iterations >= MAX_ITERATIONS { + eprintln!("Warning: DeepLLL did not converge after {} iterations", MAX_ITERATIONS); + return Some(mat); + } + iterations += 1; size_reduce(&mut mat, &mut mu, &mut b_star_sq, k); let mut c = norm_sq(&mat, k); let mut i = 1; + dbg!(&mat); while i < k { if c >= delta.clone() * b_star_sq[i - 1].clone() { let mu_ki = mu[k - 1][i - 1].clone(); @@ -26,10 +34,8 @@ pub fn deep_lll(mut mat: Matrix, delta: Rational) -> Option { break; } } - k += 1; } - Some(mat) }