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
dca_simulation.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3"""
4@file dca_simulation.py
5@brief DCA attack simulation against unmasked and n-share masked ML-KEM.
6@ingroup security_analysis
7
8@note Hamming-weight leakage model, not measurements from real hardware traces.
9
10Writes results/dca_simulation.json.
11
12Example:
13 from dca_simulation import run_dca_simulation
14 results = run_dca_simulation(num_traces=10000, masked=True, num_shares=3)
15
16@section dca_simulation_output Output Files
17- `results/dca_simulation.json` - Differential computation analysis (DCA) resistance simulation
18
19@section dca_simulation_usage Usage
20@code{.sh}
21python dca_simulation.py
22@endcode
23
24@author Ugur Coruh
25@copyright
26This software is provided for academic and research purposes.
27See LICENSE file for details.
28"""
29
30import numpy as np
31from scipy import stats
32import json
33from typing import Dict, List, Tuple
34from tqdm import tqdm
35import warnings
36
37warnings.filterwarnings("ignore")
38
39# ML-KEM parameters
40Q = 3329
41N = 256
42ETA = 2
43ZETA = 17
44
45np.random.seed(42) # Reproducibility
46
47_ZP = np.zeros(256, dtype=np.int64)
48_ZP[0] = 1
49for _i in range(1, 256):
50 _ZP[_i] = (_ZP[_i - 1] * ZETA) % Q
51
52
53def _bitrev7(k):
54 """
55 @brief Bit-reversal of a 7-bit index (FIPS-203 NTT twiddle order).
56 @param k Index in [0, 128).
57 @return Bit-reversed 7-bit index.
58 """
59 return int(format(k & 0x7F, "07b")[::-1], 2)
60
61
62def ntt_forward(poly: np.ndarray) -> np.ndarray:
63 """
64 @brief Forward NTT: coefficient domain to NTT domain (full-range image).
65 @param poly Length-256 coefficient vector.
66 @return NTT-domain coefficient vector.
67 """
68 r = np.mod(poly, Q).astype(np.int64)
69 k, length = 1, 128
70 while length >= 2:
71 for start in range(0, 256, 2 * length):
72 zeta = _ZP[_bitrev7(k)]
73 k += 1
74 for j in range(start, start + length):
75 t = (zeta * r[j + length]) % Q
76 r[j + length] = (r[j] - t) % Q
77 r[j] = (r[j] + t) % Q
78 length //= 2
79 return r
80
81
82def generate_secret_key() -> np.ndarray:
83 """
84 @brief Generate secret key via centered binomial distribution CBD(eta=2).
85 @return Coefficient array in range {-2,-1,0,1,2}.
86 """
87 bits_a = np.random.randint(0, 2, size=(N, ETA))
88 bits_b = np.random.randint(0, 2, size=(N, ETA))
89 return bits_a.sum(axis=1) - bits_b.sum(axis=1)
90
91
92def ntt_secret() -> np.ndarray:
93 """
94 @brief Full-range NTT-domain secret shat = NTT(s), the operand the base
95 multiply actually processes (coefficient-domain smallness does not
96 carry into the NTT domain).
97 @return Full-range secret vector over Z_q.
98 """
99 return ntt_forward(generate_secret_key()) % Q
100
101
102def hamming_weight(x: np.ndarray) -> np.ndarray:
103 """
104 @brief Hamming weight of each element treated as a 12-bit value (q=3329).
105 @param x Input array.
106 @return Per-element bit count as float64.
107 """
108 x_mod = np.mod(x, Q).astype(np.uint16)
109 hw = np.zeros_like(x_mod, dtype=np.float64)
110 for i in range(12): # 12 bits for q=3329
111 hw += (x_mod >> i) & 1
112 return hw
113
114
115def simulate_unmasked_trace(secret: np.ndarray, ciphertext: np.ndarray) -> np.ndarray:
116 """
117 @brief Simulated power trace for unmasked implementation.
118 @param secret Secret key coefficients.
119 @param ciphertext Ciphertext coefficients.
120 @return Hamming-weight leakage plus Gaussian noise.
121 @note Coefficient-wise product stands in for the actual NTT multiplication.
122 """
123 intermediate = np.mod(secret * ciphertext, Q)
124 leakage = hamming_weight(intermediate) + np.random.normal(0, 1, N)
125 return leakage
126
127
129 secret: np.ndarray, ciphertext: np.ndarray, num_shares: int = 3
130) -> np.ndarray:
131 """
132 @brief Simulated power trace for n-share arithmetic-masked implementation.
133 @param secret Secret key coefficients.
134 @param ciphertext Ciphertext coefficients.
135 @param num_shares Number of arithmetic shares.
136 @return Summed independent per-share leakage.
137 @note Each share leaks independently; combined leakage reveals nothing about the secret.
138 """
139 shares = []
140 for i in range(num_shares - 1):
141 share = np.random.randint(0, Q, N)
142 shares.append(share)
143
144 # Last share completes the sum
145 last_share = np.mod(secret - sum(shares), Q)
146 shares.append(last_share)
147
148 total_leakage = np.zeros(N)
149 for share in shares:
150 intermediate = np.mod(share * ciphertext, Q)
151 leakage = hamming_weight(intermediate) + np.random.normal(0, 1, N)
152 total_leakage += leakage
153
154 return total_leakage
155
156
157def pearson_correlation(x: np.ndarray, y: np.ndarray) -> float:
158 """
159 @brief Pearson correlation coefficient; 0.0 if either input has zero variance.
160 @param x First series.
161 @param y Second series.
162 @return Correlation coefficient.
163 """
164 if np.std(x) == 0 or np.std(y) == 0:
165 return 0.0
166 return np.corrcoef(x, y)[0, 1]
167
168
169def dca_attack(traces: np.ndarray, hypotheses: np.ndarray) -> Tuple[float, int]:
170 """
171 @brief Correlation-based DCA key-recovery attack.
172 @param traces Shape (num_traces, num_points) collected traces.
173 @param hypotheses Shape (num_keys, num_traces) hypothesis values per key guess.
174 @return (max_correlation, best_key_index).
175 """
176 num_keys = hypotheses.shape[0]
177 correlations = []
178
179 for key_idx in range(num_keys):
180 hyp = hypotheses[key_idx]
181 max_corr = 0
182 for point_idx in range(traces.shape[1]):
183 trace_point = traces[:, point_idx]
184 corr = abs(pearson_correlation(hyp, trace_point))
185 if corr > max_corr:
186 max_corr = corr
187 correlations.append(max_corr)
188
189 best_key = np.argmax(correlations)
190 return correlations[best_key], best_key
191
192
194 num_traces: int = 10000, masked: bool = True, num_shares: int = 3
195) -> Dict:
196 """
197 @brief Run one DCA simulation and report correct-vs-random key correlation.
198 @param num_traces Number of traces to collect.
199 @param masked Use masked implementation when True.
200 @param num_shares Number of shares for masking.
201 @return Results dictionary.
202 """
203 impl_type = f"{num_shares}-share masked" if masked else "unmasked"
204 print(f"\n{'='*60}")
205 print(f"DCA Simulation: {impl_type}")
206 print(f"Traces: {num_traces}")
207 print(f"{'='*60}")
208
209 # Generate secret key (target): full-range NTT-domain operand shat = NTT(s)
210 secret = ntt_secret()
211
212 # Collect traces
213 print("Collecting traces...")
214 traces = []
215 ciphertexts = []
216
217 for _ in tqdm(range(num_traces), desc="Traces"):
218 ct = np.random.randint(0, Q, N)
219 ciphertexts.append(ct)
220
221 if masked:
222 trace = simulate_masked_trace(secret, ct, num_shares)
223 else:
224 trace = simulate_unmasked_trace(secret, ct)
225 traces.append(trace)
226
227 traces = np.array(traces)
228 ciphertexts = np.array(ciphertexts)
229
230 # Correlate correct-key hypothesis against random-key hypotheses.
231 # Hypothesis metric: summed Hamming weight of s*c per trace.
232 print("Computing correlations...")
233
234 # Correct key hypothesis
235 correct_hyp = []
236 for i in range(num_traces):
237 intermediate = np.mod(secret * ciphertexts[i], Q)
238 correct_hyp.append(hamming_weight(intermediate).sum())
239 correct_hyp = np.array(correct_hyp)
240
241 # Random key hypotheses
242 num_random_keys = 100
243 random_hyps = []
244 for _ in range(num_random_keys):
245 random_key = ntt_secret()
246 hyp = []
247 for i in range(num_traces):
248 intermediate = np.mod(random_key * ciphertexts[i], Q)
249 hyp.append(hamming_weight(intermediate).sum())
250 random_hyps.append(np.array(hyp))
251
252 # Average trace across all dimensions
253 avg_trace = traces.mean(axis=1)
254
255 correct_corr = abs(pearson_correlation(correct_hyp, avg_trace))
256 random_corrs = [abs(pearson_correlation(rh, avg_trace)) for rh in random_hyps]
257
258 max_random_corr = max(random_corrs)
259 mean_random_corr = np.mean(random_corrs)
260
261 print("\nResults:")
262 print(f" Correct key correlation: {correct_corr:.6f}")
263 print(f" Max random key correlation: {max_random_corr:.6f}")
264 print(f" Mean random key correlation: {mean_random_corr:.6f}")
265
266 # One-sample t-test; H0: correct_corr lies within the random-key distribution
267 t_stat, p_value = stats.ttest_1samp(random_corrs, correct_corr)
268
269 # Attack succeeds when correct-key correlation exceeds 1.5x max random
270 attack_success = correct_corr > max_random_corr * 1.5
271
272 print(f"\n t-statistic: {t_stat:.4f}")
273 print(f" p-value: {p_value:.6f}")
274 print(
275 f" Attack success: {'YES (VULNERABLE)' if attack_success else 'NO (RESISTANT)'}"
276 )
277
278 results = {
279 "implementation": impl_type,
280 "num_traces": num_traces,
281 "num_shares": num_shares if masked else 1,
282 "correct_correlation": float(correct_corr),
283 "max_random_correlation": float(max_random_corr),
284 "mean_random_correlation": float(mean_random_corr),
285 "t_statistic": float(t_stat),
286 "p_value": float(p_value),
287 "attack_success": bool(attack_success),
288 }
289
290 return results
291
292
294 num_traces_list: List[int] = [1000, 10000, 100000, 500000]
295) -> Dict:
296 """
297 @brief Run the full DCA suite comparing masked vs unmasked implementations.
298 @param num_traces_list Trace counts for the masked-implementation sweep.
299 @return Aggregated results including per-simulation records and security analysis.
300 """
301 print("=" * 70)
302 print("FULL DCA SIMULATION SUITE")
303 print("Paper: PQ-WB-KEM - MDPI Mathematics")
304 print("=" * 70)
305
306 results = {"simulations": []}
307
308 # Test unmasked with fewer traces (should break quickly)
309 print("\n" + "=" * 70)
310 print("PHASE 1: Unmasked Implementation (should be vulnerable)")
311 print("=" * 70)
312
313 for num_traces in [1000, 10000]:
314 sim_result = run_dca_simulation(num_traces, masked=False)
315 results["simulations"].append(sim_result)
316
317 # Test masked with increasing traces
318 print("\n" + "=" * 70)
319 print("PHASE 2: 3-Share Masked Implementation (should resist)")
320 print("=" * 70)
321
322 for num_traces in num_traces_list:
323 if num_traces > 100000:
324 print(f"\nNote: {num_traces} traces simulation may take a while...")
325 sim_result = run_dca_simulation(num_traces, masked=True, num_shares=3)
326 results["simulations"].append(sim_result)
327
328 # Summary
329 print("\n" + "=" * 70)
330 print("SUMMARY")
331 print("=" * 70)
332
333 print(f"\n{'Implementation':<25} {'Traces':<12} {'rho_max':<12} {'Attack':<10}")
334 print("-" * 60)
335
336 for sim in results["simulations"]:
337 impl = sim["implementation"]
338 traces = sim["num_traces"]
339 rho = sim["correct_correlation"]
340 attack = "SUCCESS" if sim["attack_success"] else "FAILED"
341 print(f"{impl:<25} {traces:<12} {rho:<12.6f} {attack:<10}")
342
343 # Security threshold analysis
344 print("\n" + "=" * 70)
345 print("SECURITY ANALYSIS")
346 print("=" * 70)
347
348 # Analyze masked implementation results
349 masked_sims = [s for s in results["simulations"] if s["num_shares"] == 3]
350 if masked_sims:
351 best = max(masked_sims, key=lambda x: x["num_traces"])
352 security_threshold = 0.01 # Correlation below this indicates resistance
353
354 print(f"Maximum trace count: {best['num_traces']}")
355 print(f"Observed rho_max: {best['correct_correlation']:.6f}")
356 print(f"Security threshold: {security_threshold}")
357 print(
358 f"Result: {'RESISTANT' if best['correct_correlation'] < security_threshold else 'VULNERABLE'}"
359 )
360
361 results["security_analysis"] = {
362 "max_traces": best["num_traces"],
363 "rho_max": best["correct_correlation"],
364 "threshold": security_threshold,
365 "resistant": best["correct_correlation"] < security_threshold,
366 }
367
368 return results
369
370
371def main():
372 """
373 @brief Entry point; runs the suite and writes results/dca_simulation.json.
374 """
375 import os
376
377 # Reduced trace counts for quick verification; full run uses up to 500K
378 results = run_full_simulation(num_traces_list=[1000, 5000, 10000])
379
380 script_dir = os.path.dirname(os.path.abspath(__file__))
381 results_dir = os.path.join(os.path.dirname(os.path.dirname(script_dir)), "results")
382 os.makedirs(results_dir, exist_ok=True)
383
384 output_file = os.path.join(results_dir, "dca_simulation.json")
385 with open(output_file, "w") as f:
386 json.dump(results, f, indent=2)
387 print(f"\nResults saved to {output_file}")
388
389
390if __name__ == "__main__":
391 main()
np.ndarray simulate_unmasked_trace(np.ndarray secret, np.ndarray ciphertext)
Simulated power trace for unmasked implementation.
Dict run_full_simulation(List[int] num_traces_list=[1000, 10000, 100000, 500000])
Run the full DCA suite comparing masked vs unmasked implementations.
float pearson_correlation(np.ndarray x, np.ndarray y)
Pearson correlation coefficient; 0.0 if either input has zero variance.
main()
Entry point; runs the suite and writes results/dca_simulation.json.
_bitrev7(k)
Bit-reversal of a 7-bit index (FIPS-203 NTT twiddle order).
np.ndarray generate_secret_key()
Generate secret key via centered binomial distribution CBD(eta=2).
np.ndarray ntt_secret()
Full-range NTT-domain secret shat = NTT(s), the operand the base multiply actually processes (coeffic...
Tuple[float, int] dca_attack(np.ndarray traces, np.ndarray hypotheses)
Correlation-based DCA key-recovery attack.
np.ndarray simulate_masked_trace(np.ndarray secret, np.ndarray ciphertext, int num_shares=3)
Simulated power trace for n-share arithmetic-masked implementation.
np.ndarray hamming_weight(np.ndarray x)
Hamming weight of each element treated as a 12-bit value (q=3329).
Dict run_dca_simulation(int num_traces=10000, bool masked=True, int num_shares=3)
Run one DCA simulation and report correct-vs-random key correlation.