PQ-WB-KEM: White-Box ML-KEM-768 1.0
PQ-WB-KEM: Toward a White-Box Construction of ML-KEM-768 with Arithmetic Masking for M2M Communications - Mathematics (MDPI)
Loading...
Searching...
No Matches
algebraic_attack_analysis.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3"""
4@file algebraic_attack_analysis.py
5@brief Algebraic attack resistance analysis for white-box ML-KEM.
6@ingroup security_analysis
7
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).
14
15@section algebraic_attack_analysis_output Output Files
16- `results/algebraic_attack_analysis.json` - BGE-style algebraic attack resistance verification
17
18@section algebraic_attack_analysis_usage Usage
19@code{.sh}
20python algebraic_attack_analysis.py
21@endcode
22
23@author Ugur Coruh
24@copyright
25This software is provided for academic and research purposes.
26See LICENSE file for details.
27"""
28
29import numpy as np
30from typing import Dict, List, Tuple, Optional
31import json
32import math
33from dataclasses import dataclass
34import time
35import warnings
36
37warnings.filterwarnings("ignore")
38
39# ML-KEM Parameters
40Q = 3329 # Prime modulus
41N = 256 # Polynomial degree
42K = 3 # Module rank for ML-KEM-768
43ETA = 2 # CBD parameter
44ZETA = 17 # Primitive 256th root of unity mod q
45
46np.random.seed(42)
47
48# NTT Implementation
49
50
51def compute_zeta_powers() -> np.ndarray:
52 """
53 @brief Compute powers of zeta for the NTT.
54 @return Array of 256 zeta powers mod q.
55 """
56 zetas = np.zeros(256, dtype=np.int64)
57 zetas[0] = 1
58 for i in range(1, 256):
59 zetas[i] = (zetas[i - 1] * ZETA) % Q
60 return zetas
61
62
63ZETA_POWERS = compute_zeta_powers()
64
65
66def _bitrev7(k):
67 """
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.
71 """
72 return int(format(k & 0x7F, "07b")[::-1], 2)
73
74
75def ntt_forward(poly: np.ndarray) -> np.ndarray:
76 """
77 @brief Forward NTT: standard domain to NTT domain.
78 @param poly Polynomial coefficients.
79 @return Coefficients in NTT domain.
80 """
81 result = poly.copy().astype(np.int64)
82 k = 1
83 length = 128
84 while length >= 2:
85 for start in range(0, 256, 2 * length):
86 zeta = ZETA_POWERS[_bitrev7(k)]
87 k += 1
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
92 length //= 2
93 return result
94
95
96def ntt_inverse(ntt_poly: np.ndarray) -> np.ndarray:
97 """
98 @brief Inverse NTT: NTT domain to standard domain.
99 @param ntt_poly Coefficients in NTT domain.
100 @return Polynomial coefficients.
101 """
102 result = ntt_poly.copy().astype(np.int64)
103 k = 127
104 length = 2
105 while length <= 128:
106 for start in range(0, 256, 2 * length):
107 zeta = ZETA_POWERS[_bitrev7(k)]
108 k -= 1
109 for j in range(start, start + length):
110 t = result[j]
111 result[j] = (t + result[j + length]) % Q
112 result[j + length] = (zeta * (result[j + length] - t)) % Q
113 length *= 2
114
115 n_inv = pow(128, Q - 2, Q) # incomplete degree-2 NTT: 7 layers, scale by 128^{-1}
116 result = (result * n_inv) % Q
117 return result
118
119
120def ntt_multiply(a_ntt: np.ndarray, b_ntt: np.ndarray) -> np.ndarray:
121 """
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.
127 """
128 # In NTT domain, multiplication is done in pairs (degree-2 extensions)
129 result = np.zeros(256, dtype=np.int64)
130 for i in range(0, 256, 2):
131 # Extension field multiplication: (a0 + a1*X) * (b0 + b1*X) mod (X^2 - gamma)
132 gamma = pow(ZETA, 2 * _bitrev7(i // 2) + 1, Q)
133
134 a0, a1 = a_ntt[i], a_ntt[i + 1]
135 b0, b1 = b_ntt[i], b_ntt[i + 1]
136
137 # (a0*b0 + gamma*a1*b1, a0*b1 + a1*b0)
138 result[i] = (a0 * b0 + gamma * a1 * b1) % Q
139 result[i + 1] = (a0 * b1 + a1 * b0) % Q
140
141 return result
142
143
144# Algebraic Attack Implementation
145
146
147@dataclass
149 """@brief Result of an algebraic attack attempt."""
150
151 success: bool
152 equations_collected: int
153 equations_needed: int
154 rank_achieved: int
155 rank_needed: int
156 time_seconds: float
157 key_recovered: Optional[np.ndarray]
158 error_norm: float
159
160
161def generate_secret_key() -> np.ndarray:
162 """
163 @brief Generate a secret key with CBD(eta=2) distribution.
164 @return Secret key coefficient vector.
165 """
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)
169
170
172 secret_ntt: np.ndarray, ciphertext_ntt: np.ndarray
173) -> np.ndarray:
174 """
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.
180 """
181 return ntt_multiply(secret_ntt, ciphertext_ntt)
182
183
184def mod_inverse(a: int, m: int) -> int:
185 """
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.
190 """
191 if a == 0:
192 return 0
193 return pow(int(a), m - 2, m) # Fermat's little theorem for prime m
194
195
197 A: np.ndarray, b: np.ndarray, q: int = Q
198) -> Tuple[Optional[np.ndarray], bool]:
199 """
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).
205 """
206 A = A.astype(np.int64) % q
207 b = b.astype(np.int64) % q
208 n_rows, n_cols = A.shape
209
210 # Augmented matrix
211 aug = np.zeros((n_rows, n_cols + 1), dtype=np.int64)
212 aug[:, :n_cols] = A
213 aug[:, n_cols] = b
214
215 # Forward elimination
216 pivot_row = 0
217 for col in range(n_cols):
218 if pivot_row >= n_rows:
219 break
220
221 # Find pivot
222 max_row = pivot_row
223 for row in range(pivot_row + 1, n_rows):
224 if aug[row, col] != 0:
225 max_row = row
226 break
227
228 if aug[max_row, col] == 0:
229 continue
230
231 # Swap rows
232 aug[[pivot_row, max_row]] = aug[[max_row, pivot_row]]
233
234 # Scale pivot row
235 pivot_val = int(aug[pivot_row, col])
236 pivot_inv = mod_inverse(pivot_val, q)
237 aug[pivot_row] = (aug[pivot_row] * pivot_inv) % q
238
239 # Eliminate column
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
244
245 pivot_row += 1
246
247 # Check if solvable (all zero rows should have zero RHS)
248 for row in range(pivot_row, n_rows):
249 if aug[row, n_cols] != 0:
250 return None, False
251
252 # Back substitution (already done in elimination above)
253 solution = np.zeros(n_cols, dtype=np.int64)
254 for col in range(min(pivot_row, n_cols)):
255 # Find the row where this column is the pivot
256 for row in range(n_rows):
257 if aug[row, col] == 1:
258 # Check if this is the only non-zero in the row (excluding RHS)
259 is_pivot_row = True
260 for other_col in range(n_cols):
261 if other_col != col and aug[row, other_col] != 0:
262 is_pivot_row = False
263 break
264 if is_pivot_row:
265 solution[col] = aug[row, n_cols]
266 break
267
268 return solution % q, True
269
270
272 input_output_pairs: List[Tuple[np.ndarray, np.ndarray]],
273 target_coefficients: int = 256,
274) -> Tuple[np.ndarray, np.ndarray]:
275 """
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.
281 """
282 num_pairs = len(input_output_pairs)
283
284 # Build coefficient matrix and output vector
285 # For each NTT component, we have 2 equations (degree-2 extensions)
286 A = np.zeros((num_pairs * N, target_coefficients), dtype=np.int64)
287 b = np.zeros(num_pairs * N, dtype=np.int64)
288
289 for pair_idx, (ct_ntt, output_ntt) in enumerate(input_output_pairs):
290 for i in range(0, N, 2):
291 comp_idx = i // 2
292 gamma = pow(ZETA, 2 * _bitrev7(comp_idx) + 1, Q)
293
294 c0, c1 = int(ct_ntt[i]), int(ct_ntt[i + 1])
295
296 row_base = pair_idx * N + i
297
298 # Equation 1: output[i] = s0*c0 + gamma*s1*c1
299 A[row_base, i] = c0
300 A[row_base, i + 1] = (gamma * c1) % Q
301 b[row_base] = int(output_ntt[i])
302
303 # Equation 2: output[i+1] = s0*c1 + s1*c0
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])
307
308 return A, b
309
310
312 secret_ntt: np.ndarray, num_queries: int = 256
313) -> AlgebraicAttackResult:
314 """
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.
319 """
320 start_time = time.time()
321
322 # Collect input-output pairs
323 io_pairs = []
324 for _ in range(num_queries):
325 ct = np.random.randint(0, Q, N)
326 ct_ntt = ntt_forward(ct)
327 output_ntt = simulate_whitebox_table_lookup(secret_ntt, ct_ntt)
328 io_pairs.append((ct_ntt, output_ntt))
329
330 # Extract linear equations
331 A, b = extract_linear_equations(io_pairs)
332
333 # Analyze system rank (approximate for large matrices)
334 try:
335 rank = np.linalg.matrix_rank(A.astype(np.float64) % Q)
336 except np.linalg.LinAlgError:
337 # SVD did not converge: record the failure rather than fabricating a
338 # full-rank value. Any other exception is a bug and propagates.
339 rank = -1
340
341 # Solve over Z_q. solve_linear_system_mod_q returns (None, False) for an
342 # unsolvable system -- the legitimate "attack failed" outcome, handled by the
343 # else branch below. It does not raise for that case, so an exception here is
344 # a bug and must propagate rather than be silently reported as a failed attack.
345 recovered, solvable = solve_linear_system_mod_q(A, b, Q)
346 if solvable and recovered is not None:
347 # Check solution quality
348 error_norm = np.linalg.norm((recovered - secret_ntt) % Q)
349 success = error_norm < 1.0 # Should be exact if system is solvable
350 else:
351 error_norm = float("inf")
352 success = False
353
354 elapsed = time.time() - start_time
355
357 success=success,
358 equations_collected=len(b),
359 equations_needed=N,
360 rank_achieved=rank,
361 rank_needed=N,
362 time_seconds=elapsed,
363 key_recovered=recovered.astype(np.int64) if recovered is not None else None,
364 error_norm=error_norm,
365 )
366
367
368# Countermeasures
369
370
371def apply_nonlinear_mixing(ntt_poly: np.ndarray, mixing_key: np.ndarray) -> np.ndarray:
372 """
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.
377 """
378 # x -> (x + key)^3 mod q; the cubic map is nonlinear over Z_q
379 result = ntt_poly.copy()
380 for i in range(N):
381 x = (ntt_poly[i] + mixing_key[i]) % Q
382 result[i] = pow(int(x), 3, Q)
383 return result
384
385
386def apply_random_shuffling(ntt_poly: np.ndarray, permutation: np.ndarray) -> np.ndarray:
387 """
388 @brief Apply coefficient shuffling by a permutation.
389 @param ntt_poly Input polynomial.
390 @param permutation Index permutation.
391 @return Permuted polynomial.
392 """
393 return ntt_poly[permutation]
394
395
397 secret_ntt: np.ndarray,
398 ciphertext_ntt: np.ndarray,
399 mixing_key: np.ndarray,
400 permutation: np.ndarray,
401 inverse_permutation: np.ndarray,
402) -> np.ndarray:
403 """
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.
417 """
418 secret_mixed = apply_nonlinear_mixing(secret_ntt, mixing_key)
419 effective_secret = apply_random_shuffling(secret_mixed, permutation)
420
421 return ntt_multiply(effective_secret, ciphertext_ntt)
422
423
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:
431 """
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.
439 """
440 start_time = time.time()
441
442 # Collect input-output pairs
443 io_pairs = []
444 for _ in range(num_queries):
445 ct = np.random.randint(0, Q, N)
446 ct_ntt = ntt_forward(ct)
447 output_ntt = simulate_protected_whitebox(
448 secret_ntt, ct_ntt, mixing_key, permutation, inverse_permutation
449 )
450 io_pairs.append((ct_ntt, output_ntt))
451
452 # Extract linear equations (these should NOT form a solvable system)
453 A, b = extract_linear_equations(io_pairs)
454
455 # Analyze system rank
456 try:
457 rank = np.linalg.matrix_rank(A.astype(np.float64) % Q)
458 except np.linalg.LinAlgError:
459 # SVD did not converge: record the failure rather than fabricating a
460 # full-rank value. Any other exception is a bug and propagates.
461 rank = -1
462
463 # Solve over Z_q. An unsolvable system returns (None, False) below -- the
464 # expected outcome against the protected white-box, handled by the else
465 # branch. The solver does not raise for that, so an exception here is a bug
466 # and must propagate rather than be silently recorded as a failed attack.
467 recovered, solvable = solve_linear_system_mod_q(A, b, Q)
468 if solvable and recovered is not None:
469 # Check solution quality - should be poor due to nonlinearity
470 error_norm = np.linalg.norm((recovered - secret_ntt) % Q)
471 success = error_norm < 1.0
472 else:
473 error_norm = float("inf")
474 success = False
475
476 elapsed = time.time() - start_time
477
479 success=success,
480 equations_collected=len(b),
481 equations_needed=N,
482 rank_achieved=rank,
483 rank_needed=N,
484 time_seconds=elapsed,
485 key_recovered=recovered.astype(np.int64) if recovered is not None else None,
486 error_norm=error_norm,
487 )
488
489
490# Comprehensive Analysis
491
492
493def analyze_attack_complexity(num_trials: int = 10) -> Dict:
494 """
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.
498 """
499 print("=" * 70)
500 print("ALGEBRAIC ATTACK ANALYSIS FOR WHITE-BOX ML-KEM")
501 print("=" * 70)
502
503 results = {"parameters": {"q": Q, "n": N, "k": K, "eta": ETA}, "attacks": []}
504
505 # Test 1: Unprotected implementation
506 print("\n[TEST 1] Unprotected White-Box (NTT Linearity Exploitable)")
507 print("-" * 50)
508
509 unprotected_results = []
510 for trial in range(num_trials):
511 secret = generate_secret_key()
512 secret_ntt = ntt_forward(secret)
513
514 result = algebraic_attack_basic(secret_ntt, num_queries=2) # Minimal queries
515 unprotected_results.append(result)
516
517 if trial == 0:
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}")
523
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])
527
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}")
531
532 results["attacks"].append(
533 {
534 "type": "unprotected",
535 "success_rate": success_rate,
536 "avg_time_ms": avg_time * 1000,
537 "avg_error_norm": avg_error,
538 "queries_needed": 2,
539 "vulnerable": success_rate > 0.5,
540 }
541 )
542
543 # Test 2: Protected implementation
544 print("\n[TEST 2] Protected White-Box (Nonlinear Mixing + Shuffling)")
545 print("-" * 50)
546
547 protected_results = []
548 for trial in range(num_trials):
549 secret = generate_secret_key()
550 secret_ntt = ntt_forward(secret)
551
552 mixing_key = np.random.randint(0, Q, N)
553 permutation = np.random.permutation(N)
554 inverse_permutation = np.argsort(permutation)
555
557 secret_ntt,
558 mixing_key,
559 permutation,
560 inverse_permutation,
561 num_queries=100, # More queries to try harder
562 )
563 protected_results.append(result)
564
565 if trial == 0:
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}")
570
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])
574
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}")
578
579 results["attacks"].append(
580 {
581 "type": "protected",
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,
588 }
589 )
590
591 # Test 3: Varying query counts for unprotected
592 print("\n[TEST 3] Query Complexity Analysis (Unprotected)")
593 print("-" * 50)
594
595 query_counts = [1, 2, 4, 8, 16, 32]
596 query_analysis = []
597
598 for num_q in query_counts:
599 trial_results = []
600 for _ in range(5):
601 secret = generate_secret_key()
602 secret_ntt = ntt_forward(secret)
603 result = algebraic_attack_basic(secret_ntt, num_queries=num_q)
604 trial_results.append(result)
605
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])
608
609 print(
610 f" Queries={num_q:3d}: Success={success*100:5.1f}%, Avg Error={avg_err:.4f}"
611 )
612 query_analysis.append(
613 {"queries": num_q, "success_rate": success, "avg_error": avg_err}
614 )
615
616 results["query_complexity"] = query_analysis
617
618 # Summary
619 print("\n" + "=" * 70)
620 print("SUMMARY")
621 print("=" * 70)
622
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")
627
628 print("\n2. Countermeasure Effectiveness:")
629 protected_success = results["attacks"][1]["success_rate"]
630 print(
631 f" - Nonlinear mixing + shuffling: {protected_success*100:.1f}% attack success"
632 )
633 if protected_success < 0.1:
634 print(" - Countermeasures EFFECTIVE")
635 else:
636 print(" - Countermeasures INSUFFICIENT (need stronger protection)")
637
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")
642
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",
648 ]
649
650 return results
651
652
654 """
655 @brief Benchmark runtime overhead of the countermeasures vs baseline.
656 @return Results dict with per-operation timings and overhead factors.
657 """
658 print("\n" + "=" * 70)
659 print("COUNTERMEASURE OVERHEAD BENCHMARK")
660 print("=" * 70)
661
662 num_iterations = 10000
663
664 secret = generate_secret_key()
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)
669
670 # Baseline: Simple NTT multiply
671 ct = np.random.randint(0, Q, N)
672 ct_ntt = ntt_forward(ct)
673
674 start = time.time()
675 for _ in range(num_iterations):
676 _ = ntt_multiply(secret_ntt, ct_ntt)
677 baseline_time = (time.time() - start) / num_iterations
678
679 # With nonlinear mixing only
680 start = time.time()
681 for _ in range(num_iterations):
682 mixed = apply_nonlinear_mixing(secret_ntt, mixing_key)
683 _ = ntt_multiply(mixed, ct_ntt)
684 mixing_time = (time.time() - start) / num_iterations
685
686 # With shuffling only
687 start = time.time()
688 for _ in range(num_iterations):
689 shuffled = apply_random_shuffling(secret_ntt, permutation)
690 result = ntt_multiply(shuffled, ct_ntt)
691 _ = apply_random_shuffling(result, inverse_permutation)
692 shuffle_time = (time.time() - start) / num_iterations
693
694 # With both
695 start = time.time()
696 for _ in range(num_iterations):
698 secret_ntt, ct_ntt, mixing_key, permutation, inverse_permutation
699 )
700 full_protection_time = (time.time() - start) / num_iterations
701
702 results = {
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,
710 }
711
712 print("\nOperation times (microseconds):")
713 print(f" Baseline NTT multiply: {results['baseline_us']:8.2f} us")
714 print(
715 f" With nonlinear mixing: {results['nonlinear_mixing_us']:8.2f} us ({results['overhead_mixing']:.1f}x)"
716 )
717 print(
718 f" With shuffling: {results['shuffling_us']:8.2f} us ({results['overhead_shuffling']:.1f}x)"
719 )
720 print(
721 f" Full protection: {results['full_protection_us']:8.2f} us ({results['overhead_full']:.1f}x)"
722 )
723
724 return results
725
726
727def solve_mod_q(A: np.ndarray, b: np.ndarray, q: int):
728 """
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.
734 """
735 A = (A.copy() % q).astype(np.int64)
736 b = (b.copy() % q).astype(np.int64)
737 m, ncols = A.shape
738 row = 0
739 pivots = []
740 for col in range(ncols):
741 piv = next((r for r in range(row, m) if A[r, col] % q != 0), -1)
742 if piv == -1:
743 continue
744 A[[row, piv]] = A[[piv, row]]
745 b[[row, piv]] = b[[piv, row]]
746 inv = mod_inverse(int(A[row, col]), q)
747 A[row] = (A[row] * inv) % q
748 b[row] = (b[row] * inv) % q
749 for r in range(m):
750 if r != row and A[r, col] % q != 0:
751 f = int(A[r, col])
752 A[r] = (A[r] - f * A[row]) % q
753 b[r] = (b[r] - f * b[row]) % q
754 pivots.append(col)
755 row += 1
756 if row == ncols:
757 break
758 rank = len(pivots)
759 if rank < ncols:
760 return None, rank
761 x = np.zeros(ncols, dtype=np.int64)
762 for idx, col in enumerate(pivots):
763 x[col] = b[idx] % q
764 return x, rank
765
766
767def full_module_recovery(num_queries: int = 3, seed: int = 42) -> Dict:
768 """
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.
779 """
780 rng = np.random.default_rng(seed)
781 k, num_components = 3, N // 2
782 total_unknowns = k * N
783 recovered = 0
784 full_rank_components = 0
785 for _ in range(k):
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])
792 rows, rhs = [], []
793 for ct in queries:
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)
800 if rank == 2:
801 full_rank_components += 1
802 if sol is not None and (int(sol[0]) % Q, int(sol[1]) % Q) == (
803 s0 % Q,
804 s1 % Q,
805 ):
806 recovered += 2
807 return {
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",
816 }
817
818
819def main():
820 """@brief Run the full analysis and write results JSON."""
821 import os
822
823 print("=" * 70)
824 print("ALGEBRAIC ATTACK ANALYSIS FOR WHITE-BOX ML-KEM")
825 print("Paper: PQ-WB-KEM - MDPI Mathematics")
826 print("=" * 70)
827
828 attack_results = analyze_attack_complexity(num_trials=10)
829
830 overhead_results = benchmark_countermeasure_overhead()
831
832 # Full ML-KEM-768 module recovery on the unprotected implementation
833 module_recovery = full_module_recovery(num_queries=3)
834 print(
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']})"
839 )
840
841 full_results = {
842 **attack_results,
843 "overhead_benchmark": overhead_results,
844 "full_module_recovery": module_recovery,
845 }
846
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)
850
851 output_file = os.path.join(results_dir, "algebraic_attack_analysis.json")
852 with open(output_file, "w") as f:
853
854 def convert(obj):
855 if isinstance(obj, np.ndarray):
856 return obj.tolist()
857 if isinstance(obj, np.integer):
858 return int(obj)
859 if isinstance(obj, np.floating):
860 obj = float(obj)
861 if isinstance(obj, float) and not math.isfinite(obj):
862 # RFC 8259 has no Infinity/NaN literal; serialize as a string token.
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]
868 return obj
869
870 json.dump(convert(full_results), f, indent=2, allow_nan=False)
871
872 print(f"\n\nResults saved to {output_file}")
873 print("\nThis data should be included in the paper's security analysis section.")
874
875
876if __name__ == "__main__":
877 main()
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.