5@brief DCA attack simulation against unmasked and n-share masked ML-KEM.
6@ingroup security_analysis
8@note Hamming-weight leakage model, not measurements from real hardware traces.
10Writes results/dca_simulation.json.
13 from dca_simulation
import run_dca_simulation
16@section dca_simulation_output Output Files
17- `results/dca_simulation.json` - Differential computation analysis (DCA) resistance simulation
19@section dca_simulation_usage Usage
21python dca_simulation.py
26This software
is provided
for academic
and research purposes.
27See LICENSE file
for details.
31from scipy import stats
33from typing import Dict, List, Tuple
37warnings.filterwarnings("ignore")
47_ZP = np.zeros(256, dtype=np.int64)
49for _i
in range(1, 256):
50 _ZP[_i] = (_ZP[_i - 1] * ZETA) % Q
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.
59 return int(format(k & 0x7F,
"07b")[::-1], 2)
62def ntt_forward(poly: np.ndarray) -> np.ndarray:
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.
68 r = np.mod(poly, Q).astype(np.int64)
71 for start
in range(0, 256, 2 * length):
74 for j
in range(start, start + length):
75 t = (zeta * r[j + length]) % Q
76 r[j + length] = (r[j] - t) % Q
84 @brief Generate secret key via centered binomial distribution CBD(eta=2).
85 @return Coefficient array
in range {-2,-1,0,1,2}.
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)
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.
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.
108 x_mod = np.mod(x, Q).astype(np.uint16)
109 hw = np.zeros_like(x_mod, dtype=np.float64)
111 hw += (x_mod >> i) & 1
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.
123 intermediate = np.mod(secret * ciphertext, Q)
124 leakage = hamming_weight(intermediate) + np.random.normal(0, 1, N)
129 secret: np.ndarray, ciphertext: np.ndarray, num_shares: int = 3
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.
140 for i
in range(num_shares - 1):
141 share = np.random.randint(0, Q, N)
145 last_share = np.mod(secret - sum(shares), Q)
146 shares.append(last_share)
148 total_leakage = np.zeros(N)
150 intermediate = np.mod(share * ciphertext, Q)
151 leakage =
hamming_weight(intermediate) + np.random.normal(0, 1, N)
152 total_leakage += leakage
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.
164 if np.std(x) == 0
or np.std(y) == 0:
166 return np.corrcoef(x, y)[0, 1]
169def dca_attack(traces: np.ndarray, hypotheses: np.ndarray) -> Tuple[float, int]:
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).
176 num_keys = hypotheses.shape[0]
179 for key_idx
in range(num_keys):
180 hyp = hypotheses[key_idx]
182 for point_idx
in range(traces.shape[1]):
183 trace_point = traces[:, point_idx]
187 correlations.append(max_corr)
189 best_key = np.argmax(correlations)
190 return correlations[best_key], best_key
194 num_traces: int = 10000, masked: bool =
True, num_shares: int = 3
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.
203 impl_type = f"{num_shares}-share masked" if masked
else "unmasked"
205 print(f
"DCA Simulation: {impl_type}")
206 print(f
"Traces: {num_traces}")
213 print(
"Collecting traces...")
217 for _
in tqdm(range(num_traces), desc=
"Traces"):
218 ct = np.random.randint(0, Q, N)
219 ciphertexts.append(ct)
227 traces = np.array(traces)
228 ciphertexts = np.array(ciphertexts)
232 print(
"Computing correlations...")
236 for i
in range(num_traces):
237 intermediate = np.mod(secret * ciphertexts[i], Q)
239 correct_hyp = np.array(correct_hyp)
242 num_random_keys = 100
244 for _
in range(num_random_keys):
247 for i
in range(num_traces):
248 intermediate = np.mod(random_key * ciphertexts[i], Q)
250 random_hyps.append(np.array(hyp))
253 avg_trace = traces.mean(axis=1)
258 max_random_corr = max(random_corrs)
259 mean_random_corr = np.mean(random_corrs)
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}")
267 t_stat, p_value = stats.ttest_1samp(random_corrs, correct_corr)
270 attack_success = correct_corr > max_random_corr * 1.5
272 print(f
"\n t-statistic: {t_stat:.4f}")
273 print(f
" p-value: {p_value:.6f}")
275 f
" Attack success: {'YES (VULNERABLE)' if attack_success else 'NO (RESISTANT)'}"
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),
294 num_traces_list: List[int] = [1000, 10000, 100000, 500000]
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.
302 print(
"FULL DCA SIMULATION SUITE")
303 print(
"Paper: PQ-WB-KEM - MDPI Mathematics")
306 results = {
"simulations": []}
309 print(
"\n" +
"=" * 70)
310 print(
"PHASE 1: Unmasked Implementation (should be vulnerable)")
313 for num_traces
in [1000, 10000]:
315 results[
"simulations"].append(sim_result)
318 print(
"\n" +
"=" * 70)
319 print(
"PHASE 2: 3-Share Masked Implementation (should resist)")
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...")
326 results[
"simulations"].append(sim_result)
329 print(
"\n" +
"=" * 70)
333 print(f
"\n{'Implementation':<25} {'Traces':<12} {'rho_max':<12} {'Attack':<10}")
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}")
344 print(
"\n" +
"=" * 70)
345 print(
"SECURITY ANALYSIS")
349 masked_sims = [s
for s
in results[
"simulations"]
if s[
"num_shares"] == 3]
351 best = max(masked_sims, key=
lambda x: x[
"num_traces"])
352 security_threshold = 0.01
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}")
358 f
"Result: {'RESISTANT' if best['correct_correlation'] < security_threshold else 'VULNERABLE'}"
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,
373 @brief Entry point; runs the suite
and writes results/dca_simulation.json.
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)
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}")
390if __name__ ==
"__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.