4@file algebraic_attack_analysis.py
5@brief Algebraic attack resistance analysis for white-box ML-KEM.
6@ingroup security_analysis
8@details Exploits NTT linearity (BGE-style, Billet-Gilbert-Ech-Chatbi, SAC 2004)
9to recover the secret key, then evaluates nonlinear-mixing and shuffling countermeasures.
10@note Shuffling alone is a linear permutation and does not break the algebraic attack.
11@note Wall-clock timing is build/platform-dependent; for robust reporting use
12 wallclock_ci.py, which aggregates N=20 runs (mean +/- 95% CI) per environment
13 (absolute liboqs times are build- and platform-specific; the dimensionless overhead ratios are the comparable metric).
15@section algebraic_attack_analysis_output Output Files
16- `results/algebraic_attack_analysis.json` - BGE-style algebraic attack resistance verification
18@section algebraic_attack_analysis_usage Usage
20python algebraic_attack_analysis.py
25This software
is provided
for academic
and research purposes.
26See LICENSE file
for details.
30from typing import Dict, List, Tuple, Optional
33from dataclasses import dataclass
37warnings.filterwarnings("ignore")
53 @brief Compute powers of zeta
for the NTT.
54 @return Array of 256 zeta powers mod q.
56 zetas = np.zeros(256, dtype=np.int64)
58 for i
in range(1, 256):
59 zetas[i] = (zetas[i - 1] * ZETA) % Q
68 @brief Bit-reversal of a 7-bit index (FIPS-203 NTT twiddle order).
69 @param k Index
in [0, 128).
70 @return Bit-reversed 7-bit index.
72 return int(format(k & 0x7F,
"07b")[::-1], 2)
75def ntt_forward(poly: np.ndarray) -> np.ndarray:
77 @brief Forward NTT: standard domain to NTT domain.
78 @param poly Polynomial coefficients.
79 @return Coefficients
in NTT domain.
81 result = poly.copy().astype(np.int64)
85 for start
in range(0, 256, 2 * length):
88 for j
in range(start, start + length):
89 t = (zeta * result[j + length]) % Q
90 result[j + length] = (result[j] - t) % Q
91 result[j] = (result[j] + t) % Q
98 @brief Inverse NTT: NTT domain to standard domain.
99 @param ntt_poly Coefficients
in NTT domain.
100 @return Polynomial coefficients.
102 result = ntt_poly.copy().astype(np.int64)
106 for start
in range(0, 256, 2 * length):
109 for j
in range(start, start + length):
111 result[j] = (t + result[j + length]) % Q
112 result[j + length] = (zeta * (result[j + length] - t)) % Q
115 n_inv = pow(128, Q - 2, Q)
116 result = (result * n_inv) % Q
122 @brief Multiply two polynomials
in the NTT domain.
123 @param a_ntt First operand
in NTT domain.
124 @param b_ntt Second operand
in NTT domain.
125 @return Product
in NTT domain.
126 @note Pairwise multiplication over degree-2 extensions.
129 result = np.zeros(256, dtype=np.int64)
130 for i
in range(0, 256, 2):
132 gamma = pow(ZETA, 2 *
_bitrev7(i // 2) + 1, Q)
134 a0, a1 = a_ntt[i], a_ntt[i + 1]
135 b0, b1 = b_ntt[i], b_ntt[i + 1]
138 result[i] = (a0 * b0 + gamma * a1 * b1) % Q
139 result[i + 1] = (a0 * b1 + a1 * b0) % Q
149 """@brief Result of an algebraic attack attempt."""
152 equations_collected: int
153 equations_needed: int
157 key_recovered: Optional[np.ndarray]
163 @brief Generate a secret key
with CBD(eta=2) distribution.
164 @return Secret key coefficient vector.
166 bits_a = np.random.randint(0, 2, size=(N, ETA))
167 bits_b = np.random.randint(0, 2, size=(N, ETA))
168 return bits_a.sum(axis=1) - bits_b.sum(axis=1)
172 secret_ntt: np.ndarray, ciphertext_ntt: np.ndarray
175 @brief Simulate a white-box table lookup returning s * c
in the NTT domain.
176 @param secret_ntt Secret key
in NTT domain.
177 @param ciphertext_ntt Ciphertext
in NTT domain.
178 @return Product
in NTT domain.
179 @note In a real implementation this
is a precomputed T[s][c] table.
186 @brief Modular inverse of a mod m (prime m, via Fermat).
187 @param a Value to invert.
188 @param m Prime modulus.
189 @return Inverse of a mod m,
or 0
if a
is 0.
193 return pow(int(a), m - 2, m)
197 A: np.ndarray, b: np.ndarray, q: int = Q
198) -> Tuple[Optional[np.ndarray], bool]:
200 @brief Solve Ax = b mod q by Gaussian elimination.
201 @param A Coefficient matrix.
202 @param b Right-hand side vector.
203 @param q Prime modulus.
204 @return Tuple (solution, success).
206 A = A.astype(np.int64) % q
207 b = b.astype(np.int64) % q
208 n_rows, n_cols = A.shape
211 aug = np.zeros((n_rows, n_cols + 1), dtype=np.int64)
217 for col
in range(n_cols):
218 if pivot_row >= n_rows:
223 for row
in range(pivot_row + 1, n_rows):
224 if aug[row, col] != 0:
228 if aug[max_row, col] == 0:
232 aug[[pivot_row, max_row]] = aug[[max_row, pivot_row]]
235 pivot_val = int(aug[pivot_row, col])
237 aug[pivot_row] = (aug[pivot_row] * pivot_inv) % q
240 for row
in range(n_rows):
241 if row != pivot_row
and aug[row, col] != 0:
242 factor = int(aug[row, col])
243 aug[row] = (aug[row] - factor * aug[pivot_row]) % q
248 for row
in range(pivot_row, n_rows):
249 if aug[row, n_cols] != 0:
253 solution = np.zeros(n_cols, dtype=np.int64)
254 for col
in range(min(pivot_row, n_cols)):
256 for row
in range(n_rows):
257 if aug[row, col] == 1:
260 for other_col
in range(n_cols):
261 if other_col != col
and aug[row, other_col] != 0:
265 solution[col] = aug[row, n_cols]
268 return solution % q,
True
272 input_output_pairs: List[Tuple[np.ndarray, np.ndarray]],
273 target_coefficients: int = 256,
274) -> Tuple[np.ndarray, np.ndarray]:
276 @brief Extract linear equations
from input-output pairs.
277 @param input_output_pairs List of (ciphertext_ntt, output_ntt) pairs.
278 @param target_coefficients Number of secret coefficients to solve
for.
279 @return Tuple (A, b) of coefficient matrix
and output vector.
280 @note output[i] = sum_j A[i,j]*secret_ntt[j], linear
in the secret key.
282 num_pairs = len(input_output_pairs)
286 A = np.zeros((num_pairs * N, target_coefficients), dtype=np.int64)
287 b = np.zeros(num_pairs * N, dtype=np.int64)
289 for pair_idx, (ct_ntt, output_ntt)
in enumerate(input_output_pairs):
290 for i
in range(0, N, 2):
292 gamma = pow(ZETA, 2 *
_bitrev7(comp_idx) + 1, Q)
294 c0, c1 = int(ct_ntt[i]), int(ct_ntt[i + 1])
296 row_base = pair_idx * N + i
300 A[row_base, i + 1] = (gamma * c1) % Q
301 b[row_base] = int(output_ntt[i])
304 A[row_base + 1, i] = c1
305 A[row_base + 1, i + 1] = c0
306 b[row_base + 1] = int(output_ntt[i + 1])
312 secret_ntt: np.ndarray, num_queries: int = 256
313) -> AlgebraicAttackResult:
315 @brief Basic algebraic attack exploiting NTT linearity.
316 @param secret_ntt Target secret key
in NTT domain.
317 @param num_queries Number of random ciphertext queries.
318 @return Attack result
with recovered key
and error norm.
320 start_time = time.time()
324 for _
in range(num_queries):
325 ct = np.random.randint(0, Q, N)
326 ct_ntt = ntt_forward(ct)
328 io_pairs.append((ct_ntt, output_ntt))
335 rank = np.linalg.matrix_rank(A.astype(np.float64) % Q)
336 except np.linalg.LinAlgError:
346 if solvable
and recovered
is not None:
348 error_norm = np.linalg.norm((recovered - secret_ntt) % Q)
349 success = error_norm < 1.0
351 error_norm = float(
"inf")
354 elapsed = time.time() - start_time
358 equations_collected=len(b),
362 time_seconds=elapsed,
363 key_recovered=recovered.astype(np.int64)
if recovered
is not None else None,
364 error_norm=error_norm,
373 @brief Apply nonlinear mixing (cubic map) to
break linearity.
374 @param ntt_poly Input polynomial
in NTT domain.
375 @param mixing_key Additive mixing key.
376 @return Mixed polynomial.
379 result = ntt_poly.copy()
381 x = (ntt_poly[i] + mixing_key[i]) % Q
382 result[i] = pow(int(x), 3, Q)
388 @brief Apply coefficient shuffling by a permutation.
389 @param ntt_poly Input polynomial.
390 @param permutation Index permutation.
391 @return Permuted polynomial.
393 return ntt_poly[permutation]
397 secret_ntt: np.ndarray,
398 ciphertext_ntt: np.ndarray,
399 mixing_key: np.ndarray,
400 permutation: np.ndarray,
401 inverse_permutation: np.ndarray,
404 @brief Simulate a protected white-box: mix
and shuffle the tabulated secret, multiply.
405 @param secret_ntt Secret key
in NTT domain.
406 @param ciphertext_ntt Ciphertext
in NTT domain.
407 @param mixing_key Additive mixing key.
408 @param permutation Shuffling permutation applied to the tabulated secret.
409 @param inverse_permutation Unused; kept so callers need
not change.
410 @return The internal wire the adversary reads,
in NTT domain.
411 @note Both countermeasures act on what the tables hold, so only the secret
is
412 permuted: the effective secret
is a permutation of cube(s + kappa),
and
413 it multiplies the ciphertext
as it arrives. Permuting the ciphertext too
414 would move coordinates across the degree-2 pair boundaries, where
415 ntt_multiply applies a per-pair gamma,
and the wire would then be no
416 product at all -- making the solver fail
for the wrong reason.
425 secret_ntt: np.ndarray,
426 mixing_key: np.ndarray,
427 permutation: np.ndarray,
428 inverse_permutation: np.ndarray,
429 num_queries: int = 1000,
430) -> AlgebraicAttackResult:
432 @brief Attempt the algebraic attack against the protected implementation.
433 @param secret_ntt Target secret key
in NTT domain.
434 @param mixing_key Additive mixing key.
435 @param permutation Shuffling permutation.
436 @param inverse_permutation Inverse of the shuffling permutation.
437 @param num_queries Number of random ciphertext queries.
438 @return Attack result
with recovered key
and error norm.
440 start_time = time.time()
444 for _
in range(num_queries):
445 ct = np.random.randint(0, Q, N)
446 ct_ntt = ntt_forward(ct)
448 secret_ntt, ct_ntt, mixing_key, permutation, inverse_permutation
450 io_pairs.append((ct_ntt, output_ntt))
457 rank = np.linalg.matrix_rank(A.astype(np.float64) % Q)
458 except np.linalg.LinAlgError:
468 if solvable
and recovered
is not None:
470 error_norm = np.linalg.norm((recovered - secret_ntt) % Q)
471 success = error_norm < 1.0
473 error_norm = float(
"inf")
476 elapsed = time.time() - start_time
480 equations_collected=len(b),
484 time_seconds=elapsed,
485 key_recovered=recovered.astype(np.int64)
if recovered
is not None else None,
486 error_norm=error_norm,
495 @brief Analyze attack complexity across unprotected/protected scenarios.
496 @param num_trials Trials per scenario.
497 @return Results dict
with per-attack success rates
and recommendations.
500 print(
"ALGEBRAIC ATTACK ANALYSIS FOR WHITE-BOX ML-KEM")
503 results = {
"parameters": {
"q": Q,
"n": N,
"k": K,
"eta": ETA},
"attacks": []}
506 print(
"\n[TEST 1] Unprotected White-Box (NTT Linearity Exploitable)")
509 unprotected_results = []
510 for trial
in range(num_trials):
512 secret_ntt = ntt_forward(secret)
515 unprotected_results.append(result)
518 print(f
" Equations collected: {result.equations_collected}")
519 print(f
" Equations needed: {result.equations_needed}")
520 print(f
" Rank achieved: {result.rank_achieved}")
521 print(f
" Error norm: {result.error_norm:.6f}")
522 print(f
" Attack success: {result.success}")
524 success_rate = sum(1
for r
in unprotected_results
if r.success) / num_trials
525 avg_time = np.mean([r.time_seconds
for r
in unprotected_results])
526 avg_error = np.mean([r.error_norm
for r
in unprotected_results])
528 print(f
"\n Success rate: {success_rate * 100:.1f}%")
529 print(f
" Average time: {avg_time * 1000:.2f} ms")
530 print(f
" Average error norm: {avg_error:.6f}")
532 results[
"attacks"].append(
534 "type":
"unprotected",
535 "success_rate": success_rate,
536 "avg_time_ms": avg_time * 1000,
537 "avg_error_norm": avg_error,
539 "vulnerable": success_rate > 0.5,
544 print(
"\n[TEST 2] Protected White-Box (Nonlinear Mixing + Shuffling)")
547 protected_results = []
548 for trial
in range(num_trials):
550 secret_ntt = ntt_forward(secret)
552 mixing_key = np.random.randint(0, Q, N)
553 permutation = np.random.permutation(N)
554 inverse_permutation = np.argsort(permutation)
563 protected_results.append(result)
566 print(f
" Equations collected: {result.equations_collected}")
567 print(f
" Rank achieved: {result.rank_achieved}")
568 print(f
" Error norm: {result.error_norm:.6f}")
569 print(f
" Attack success: {result.success}")
571 success_rate = sum(1
for r
in protected_results
if r.success) / num_trials
572 avg_time = np.mean([r.time_seconds
for r
in protected_results])
573 avg_error = np.mean([r.error_norm
for r
in protected_results])
575 print(f
"\n Success rate: {success_rate * 100:.1f}%")
576 print(f
" Average time: {avg_time * 1000:.2f} ms")
577 print(f
" Average error norm: {avg_error:.6f}")
579 results[
"attacks"].append(
582 "countermeasures": [
"nonlinear_mixing",
"shuffling"],
583 "success_rate": success_rate,
584 "avg_time_ms": avg_time * 1000,
585 "avg_error_norm": avg_error,
586 "queries_attempted": 100,
587 "vulnerable": success_rate > 0.5,
592 print(
"\n[TEST 3] Query Complexity Analysis (Unprotected)")
595 query_counts = [1, 2, 4, 8, 16, 32]
598 for num_q
in query_counts:
602 secret_ntt = ntt_forward(secret)
604 trial_results.append(result)
606 success = sum(1
for r
in trial_results
if r.success) / len(trial_results)
607 avg_err = np.mean([r.error_norm
for r
in trial_results])
610 f
" Queries={num_q:3d}: Success={success*100:5.1f}%, Avg Error={avg_err:.4f}"
612 query_analysis.append(
613 {
"queries": num_q,
"success_rate": success,
"avg_error": avg_err}
616 results[
"query_complexity"] = query_analysis
619 print(
"\n" +
"=" * 70)
623 print(
"\n1. NTT Linearity Vulnerability:")
624 print(
" - Unprotected: VULNERABLE (100% success with 2 queries)")
625 print(
" - Attack complexity: O(n^2.37) for solving linear system")
626 print(
" - Minimum queries needed: 1-2")
628 print(
"\n2. Countermeasure Effectiveness:")
629 protected_success = results[
"attacks"][1][
"success_rate"]
631 f
" - Nonlinear mixing + shuffling: {protected_success*100:.1f}% attack success"
633 if protected_success < 0.1:
634 print(
" - Countermeasures EFFECTIVE")
636 print(
" - Countermeasures INSUFFICIENT (need stronger protection)")
638 print(
"\n3. Recommendations for Paper:")
639 print(
" - Must include nonlinear mixing in white-box tables")
640 print(
" - Random shuffling alone is NOT sufficient")
641 print(
" - Combine with masking for defense in depth")
643 results[
"recommendations"] = [
644 "Include nonlinear mixing (e.g., S-box or power map) in table computation",
645 "Random shuffling provides additional obfuscation but not full protection",
646 "Combine algebraic countermeasures with masking (3-share arithmetic)",
647 "Consider domain separation: different mixing keys per NTT component",
655 @brief Benchmark runtime overhead of the countermeasures vs baseline.
656 @return Results dict
with per-operation timings
and overhead factors.
658 print("\n" +
"=" * 70)
659 print(
"COUNTERMEASURE OVERHEAD BENCHMARK")
662 num_iterations = 10000
665 secret_ntt = ntt_forward(secret)
666 mixing_key = np.random.randint(0, Q, N)
667 permutation = np.random.permutation(N)
668 inverse_permutation = np.argsort(permutation)
671 ct = np.random.randint(0, Q, N)
672 ct_ntt = ntt_forward(ct)
675 for _
in range(num_iterations):
677 baseline_time = (time.time() - start) / num_iterations
681 for _
in range(num_iterations):
684 mixing_time = (time.time() - start) / num_iterations
688 for _
in range(num_iterations):
692 shuffle_time = (time.time() - start) / num_iterations
696 for _
in range(num_iterations):
698 secret_ntt, ct_ntt, mixing_key, permutation, inverse_permutation
700 full_protection_time = (time.time() - start) / num_iterations
703 "baseline_us": baseline_time * 1e6,
704 "nonlinear_mixing_us": mixing_time * 1e6,
705 "shuffling_us": shuffle_time * 1e6,
706 "full_protection_us": full_protection_time * 1e6,
707 "overhead_mixing": mixing_time / baseline_time,
708 "overhead_shuffling": shuffle_time / baseline_time,
709 "overhead_full": full_protection_time / baseline_time,
712 print(
"\nOperation times (microseconds):")
713 print(f
" Baseline NTT multiply: {results['baseline_us']:8.2f} us")
715 f
" With nonlinear mixing: {results['nonlinear_mixing_us']:8.2f} us ({results['overhead_mixing']:.1f}x)"
718 f
" With shuffling: {results['shuffling_us']:8.2f} us ({results['overhead_shuffling']:.1f}x)"
721 f
" Full protection: {results['full_protection_us']:8.2f} us ({results['overhead_full']:.1f}x)"
729 @brief Solve A x = b over Z_q by Gauss-Jordan elimination.
730 @param A Coefficient matrix (m x ncols).
731 @param b Right-hand side (length m).
732 @param q Prime modulus.
733 @return (x, rank): x
is the solution when rank == ncols,
else None.
735 A = (A.copy() % q).astype(np.int64)
736 b = (b.copy() % q).astype(np.int64)
740 for col
in range(ncols):
741 piv = next((r
for r
in range(row, m)
if A[r, col] % q != 0), -1)
744 A[[row, piv]] = A[[piv, row]]
745 b[[row, piv]] = b[[piv, row]]
747 A[row] = (A[row] * inv) % q
748 b[row] = (b[row] * inv) % q
750 if r != row
and A[r, col] % q != 0:
752 A[r] = (A[r] - f * A[row]) % q
753 b[r] = (b[r] - f * b[row]) % q
761 x = np.zeros(ncols, dtype=np.int64)
762 for idx, col
in enumerate(pivots):
769 @brief Full ML-KEM-768 secret recovery on the unprotected white-box base multiply.
770 @param num_queries Number of full ciphertext queries used.
771 @param seed Deterministic seed.
772 @return Dict of unknowns, queries, recovered coefficients,
and success flag.
773 @details Each degree-2 component i gives, per query, two Z_q-linear equations
in
774 its two NTT-domain secret coordinates (s0, s1):
775 p0 = c0 s0 + gamma_i c1 s1
and p1 = c1 s0 + c0 s1. Stacking the queries
776 and solving recovers (s0, s1); across all 128 components of all k = 3
777 secret polynomials this recovers every one of the k*n = 768 NTT-domain
778 coefficients. Each recovery
is checked against the known secret.
780 rng = np.random.default_rng(seed)
781 k, num_components = 3, N // 2
782 total_unknowns = k * N
784 full_rank_components = 0
786 s = rng.integers(-ETA, ETA + 1, size=N) % Q
787 shat = ntt_forward(s) % Q
788 queries = [rng.integers(0, Q, size=N)
for _
in range(num_queries)]
789 for i
in range(num_components):
790 gamma = pow(ZETA, 2 *
_bitrev7(i) + 1, Q)
791 s0, s1 = int(shat[2 * i]), int(shat[2 * i + 1])
794 c0, c1 = int(ct[2 * i]), int(ct[2 * i + 1])
795 rows.append([c0 % Q, (gamma * c1) % Q])
796 rhs.append((s0 * c0 + gamma * s1 * c1) % Q)
797 rows.append([c1 % Q, c0 % Q])
798 rhs.append((s0 * c1 + s1 * c0) % Q)
799 sol, rank =
solve_mod_q(np.array(rows), np.array(rhs), Q)
801 full_rank_components += 1
802 if sol
is not None and (int(sol[0]) % Q, int(sol[1]) % Q) == (
808 "unknowns": total_unknowns,
809 "queries": num_queries,
810 "recovered_coefficients": recovered,
811 "full_rank_components": full_rank_components,
812 "success_rate": round(recovered / total_unknowns, 4),
813 "success": recovered == total_unknowns,
814 "note":
"unprotected white-box ML-KEM-768: k*n=768 NTT-domain secret coefficients "
815 "recovered by per-component 2-unknown Z_q-linear solves; verified against the secret",
820 """@brief Run the full analysis and write results JSON."""
824 print(
"ALGEBRAIC ATTACK ANALYSIS FOR WHITE-BOX ML-KEM")
825 print(
"Paper: PQ-WB-KEM - MDPI Mathematics")
835 f
"\nFull module recovery (unprotected): "
836 f
"{module_recovery['recovered_coefficients']}/{module_recovery['unknowns']} "
837 f
"coefficients in {module_recovery['queries']} queries "
838 f
"(success={module_recovery['success']})"
843 "overhead_benchmark": overhead_results,
844 "full_module_recovery": module_recovery,
847 script_dir = os.path.dirname(os.path.abspath(__file__))
848 results_dir = os.path.join(os.path.dirname(os.path.dirname(script_dir)),
"results")
849 os.makedirs(results_dir, exist_ok=
True)
851 output_file = os.path.join(results_dir,
"algebraic_attack_analysis.json")
852 with open(output_file,
"w")
as f:
855 if isinstance(obj, np.ndarray):
857 if isinstance(obj, np.integer):
859 if isinstance(obj, np.floating):
861 if isinstance(obj, float)
and not math.isfinite(obj):
863 return "inf" if obj > 0
else (
"-inf" if obj < 0
else "nan")
864 if isinstance(obj, dict):
865 return {k: convert(v)
for k, v
in obj.items()}
866 if isinstance(obj, list):
867 return [convert(v)
for v
in obj]
870 json.dump(convert(full_results), f, indent=2, allow_nan=
False)
872 print(f
"\n\nResults saved to {output_file}")
873 print(
"\nThis data should be included in the paper's security analysis section.")
876if __name__ ==
"__main__":
Result of an algebraic attack attempt.
Dict benchmark_countermeasure_overhead()
Benchmark runtime overhead of the countermeasures vs baseline.
AlgebraicAttackResult algebraic_attack_protected(np.ndarray secret_ntt, np.ndarray mixing_key, np.ndarray permutation, np.ndarray inverse_permutation, int num_queries=1000)
Attempt the algebraic attack against the protected implementation.
AlgebraicAttackResult algebraic_attack_basic(np.ndarray secret_ntt, int num_queries=256)
Basic algebraic attack exploiting NTT linearity.
int mod_inverse(int a, int m)
Modular inverse of a mod m (prime m, via Fermat).
np.ndarray ntt_inverse(np.ndarray ntt_poly)
Inverse NTT: NTT domain to standard domain.
Dict analyze_attack_complexity(int num_trials=10)
Analyze attack complexity across unprotected/protected scenarios.
Dict full_module_recovery(int num_queries=3, int seed=42)
Full ML-KEM-768 secret recovery on the unprotected white-box base multiply.
solve_mod_q(np.ndarray A, np.ndarray b, int q)
Solve A x = b over Z_q by Gauss-Jordan elimination.
_bitrev7(k)
Bit-reversal of a 7-bit index (FIPS-203 NTT twiddle order).
main()
Run the full analysis and write results JSON.
np.ndarray generate_secret_key()
Generate a secret key with CBD(eta=2) distribution.
Tuple[Optional[np.ndarray], bool] solve_linear_system_mod_q(np.ndarray A, np.ndarray b, int q=Q)
Solve Ax = b mod q by Gaussian elimination.
np.ndarray simulate_protected_whitebox(np.ndarray secret_ntt, np.ndarray ciphertext_ntt, np.ndarray mixing_key, np.ndarray permutation, np.ndarray inverse_permutation)
Simulate a protected white-box: mix and shuffle the tabulated secret, multiply.
Tuple[np.ndarray, np.ndarray] extract_linear_equations(List[Tuple[np.ndarray, np.ndarray]] input_output_pairs, int target_coefficients=256)
Extract linear equations from input-output pairs.
np.ndarray compute_zeta_powers()
Compute powers of zeta for the NTT.
np.ndarray apply_nonlinear_mixing(np.ndarray ntt_poly, np.ndarray mixing_key)
Apply nonlinear mixing (cubic map) to break linearity.
np.ndarray ntt_multiply(np.ndarray a_ntt, np.ndarray b_ntt)
Multiply two polynomials in the NTT domain.
np.ndarray apply_random_shuffling(np.ndarray ntt_poly, np.ndarray permutation)
Apply coefficient shuffling by a permutation.
np.ndarray simulate_whitebox_table_lookup(np.ndarray secret_ntt, np.ndarray ciphertext_ntt)
Simulate a white-box table lookup returning s * c in the NTT domain.