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
concrete_security_bounds.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3"""
4@file concrete_security_bounds.py
5@brief Engineering security-estimate calculator for white-box ML-KEM-768.
6@ingroup security_analysis
7
8@details Naive engineering estimates plus the core's byte-read footprint. The DCA
9correlation sits near the sampling-noise floor (a measurement-resolution lower bound, not a
10security proof) and timing immunity is structural (constant-time construction), not a
11CoV/bit figure. The footprint (log2 of total core bytes) is a SIZE, not a bound: the core
12has entry-determinacy degree <= 1, so an adversary regenerates it from |s_hat| without
13reading it (entry_determinacy.py, table_extraction_witness.py).
14Writes results/concrete_security_bounds.json.
15@note All inputs are read from the committed experiment JSONs (dca_simulation.json,
16whitebox_reference.json, whitebox_encoded.json); a missing input is a hard error --
17no reference value is silently substituted.
18
19@section concrete_security_bounds_output Output Files
20- `results/concrete_security_bounds.json` - DCA and timing engineering estimates plus the core byte-read footprint
21
22@section concrete_security_bounds_usage Usage
23@code{.sh}
24python concrete_security_bounds.py
25@endcode
26
27@author Ugur Coruh
28@copyright
29This software is provided for academic and research purposes.
30See LICENSE file for details.
31"""
32
33import json
34import math
35import os
36from datetime import datetime
37from typing import Dict, Any
38
39# ML-KEM-768 parameters
40ML_KEM_768_PARAMS = {
41 "n": 256,
42 "k": 3,
43 "q": 3329,
44 "eta1": 2,
45 "eta2": 2,
46}
47
48# White-box implementation parameters. The base-multiply operand is the full-range
49# NTT-domain secret. Footprints are not hardcoded here: they are derived at runtime
50# from the measured base tables (whitebox_reference.json) plus the measured 3.41 MB
51# encoding sublayer (whitebox_encoded.json) -- construction A = 22.16 + 3.41 MB,
52# construction B = 7.67 + 3.41 MB (k=3). A is the larger footprint; neither is a bound.
53WB_PARAMS = {
54 "num_shares": 3,
55}
56
57
59 num_traces: int, measured_correlation: float, num_shares: int
60) -> Dict[str, Any]:
61 """
62 @brief DCA security in bits from measured correlation.
63 @param num_traces Traces used in the DCA simulation.
64 @param measured_correlation Correlation rho of the correct-key hypothesis.
65 @param num_shares Number of masking shares.
66 @return Dict of first-order, higher-order, and combined bit-security.
67 @note First-order trace complexity is estimated by the standard 1/rho^2 rule
68 (rho taken at face value); higher-order as q^(n-1). Because rho sits at
69 or below the 1/sqrt(num_traces) sampling-noise floor, this is an
70 engineering estimate, not a security proof.
71 """
72 # First-order trace-complexity estimate: N ~ 1/rho^2 (rho at face value).
73 if measured_correlation > 0:
74 traces_for_success = 1.0 / (measured_correlation**2)
75 else:
76 traces_for_success = float("inf")
77
78 # Sampling-noise floor at the trace budget used, and the trace-complexity
79 # lower bound certified by non-detection (rho stays below the floor).
80 noise_floor = 1.0 / math.sqrt(num_traces) if num_traces > 0 else float("inf")
81 non_detection_floor_bits = math.log2(num_traces) if num_traces > 0 else 0.0
82
83 # Bit security = log2(traces needed)
84 if traces_for_success < float("inf"):
85 first_order_bits = math.log2(traces_for_success)
86 else:
87 first_order_bits = 128
88
89 # Higher-order attack multiplier
90 q = ML_KEM_768_PARAMS["q"]
91 higher_order_multiplier = q ** (num_shares - 1)
92 higher_order_bits = math.log2(higher_order_multiplier)
93
94 # Reported first-order estimate (defensible, not a proof).
95 combined_bits = first_order_bits
96
97 return {
98 "num_traces": num_traces,
99 "measured_correlation": measured_correlation,
100 "sampling_noise_floor": round(noise_floor, 5),
101 "rho_below_floor": bool(measured_correlation <= noise_floor),
102 "non_detection_floor_bits": round(non_detection_floor_bits, 1),
103 "traces_for_first_order": (
104 int(traces_for_success) if traces_for_success < 1e15 else "inf"
105 ),
106 "first_order_bits": round(first_order_bits, 1),
107 "higher_order_multiplier_bits": round(higher_order_bits, 1),
108 "combined_security_bits": round(combined_bits, 1),
109 "security_level": f"~2^{int(combined_bits)}",
110 "note": "first-order estimate (1/rho^2); rho near the sampling floor (~1.1x); not a security proof",
111 }
112
113
114def calculate_table_footprint(table_size_bytes: int) -> Dict[str, Any]:
115 """
116 @brief Byte-read footprint of the protected core, as an engineering magnitude.
117 @param table_size_bytes Total table storage in bytes, taken from the measured artifacts.
118 @return Dict of table size and the byte-reads needed to copy it.
119 @note A SIZE, not a security bound and not an extraction cost. The core is a
120 deterministic function of the secret with entry-determinacy degree <= 1, so an
121 adversary regenerates it from |s_hat| without reading the footprint
122 (entry_determinacy.py, table_extraction_witness.py).
123 """
124 copy_operations = int(table_size_bytes) # 1 byte per read
125 copy_bits = math.log2(copy_operations)
126
127 return {
128 "table_size_bytes": int(table_size_bytes),
129 "table_size_mb": round(table_size_bytes / 1e6, 2),
130 "byte_reads_to_copy_core": copy_operations,
131 "byte_reads_to_copy_core_log2": round(copy_bits, 1),
132 "footprint_magnitude": f"~2^{round(copy_bits, 1)} byte-reads to copy",
133 "is_security_bound": False,
134 "why_not_a_security_bound": "the core is regenerable from |s_hat|; see "
135 "results/table_extraction_witness.json for the measured budget",
136 }
137
138
139def load_experimental_results(results_dir: str) -> Dict[str, Any]:
140 """
141 @brief Load DCA and overhead JSON results if present.
142 @param results_dir Directory holding the experiment JSON files.
143 @return Dict with optional "dca" and "overhead" entries.
144 """
145 results = {}
146
147 dca_file = os.path.join(results_dir, "dca_simulation.json")
148 if os.path.exists(dca_file):
149 with open(dca_file, "r") as f:
150 results["dca"] = json.load(f)
151
152 overhead_file = os.path.join(results_dir, "overhead_calculation.json")
153 if os.path.exists(overhead_file):
154 with open(overhead_file, "r") as f:
155 results["overhead"] = json.load(f)
156
157 return results
158
159
160def load_measured_footprints(results_dir: str) -> tuple:
161 """
162 @brief Derive the two construction footprints from the committed measurements.
163 @param results_dir Directory holding the experiment JSON files.
164 @return (table_bytes_A, table_bytes_B) total footprints in BYTES.
165 @details A = measured base table (whitebox_reference.json, A_shared_full_table)
166 plus the measured encoding sublayer (whitebox_encoded.json); B likewise
167 with the baked per-component table. Absence is a hard error -- no value
168 is hardcoded or substituted.
169 @note Bytes, not MB: the producers emit both, and routing through a 2-decimal MB
170 figure both loses precision and invites a MB/MiB confusion at the conversion.
171 """
172 ref_file = os.path.join(results_dir, "whitebox_reference.json")
173 enc_file = os.path.join(results_dir, "whitebox_encoded.json")
174 if not os.path.exists(ref_file):
175 raise RuntimeError(
176 "results/whitebox_reference.json missing; run whitebox_reference.py "
177 "first (base-table footprints are read from it, not hardcoded)."
178 )
179 if not os.path.exists(enc_file):
180 raise RuntimeError(
181 "results/whitebox_encoded.json missing; run whitebox_encoded.py "
182 "first (the encoding-sublayer footprint is read from it)."
183 )
184 with open(ref_file, "r") as f:
185 ref = json.load(f)["constructions"]
186 with open(enc_file, "r") as f:
187 enc = json.load(f)
188 encoding_bytes = int(enc["storage"]["encoding_tables_bytes"])
189 base_a = int(ref["A_shared_full_table"]["total_bytes"])
190 base_b = int(ref["B_baked_per_component"]["total_bytes"])
191 return base_a + encoding_bytes, base_b + encoding_bytes
192
193
194def main():
195 """
196 @brief Compute all bounds, print the summary, and write the JSON output.
197 @return Dict of parameters, inputs, and security bounds.
198 """
199
200 print("=" * 70)
201 print("CONCRETE SECURITY BOUNDS CALCULATOR")
202 print("PQ-WB-KEM: White-Box ML-KEM-768")
203 print("Paper: MDPI Mathematics")
204 print("=" * 70)
205 print(f"Timestamp: {datetime.now()}")
206 print()
207
208 script_dir = os.path.dirname(os.path.abspath(__file__))
209 project_root = os.path.dirname(os.path.dirname(script_dir))
210 results_dir = os.path.join(project_root, "results")
211
212 # DCA correlation: authoritative measured value from the committed simulation.
213 # Absence is a hard error -- no hardcoded fallback (the manuscript's rho is this value).
214 exp_results = load_experimental_results(results_dir)
215 if "dca" not in exp_results:
216 raise RuntimeError(
217 "results/dca_simulation.json missing; run dca_simulation.py first "
218 "(concrete_security_bounds.py substitutes no fallback correlation)."
219 )
220 measured_correlation = None
221 for sim in exp_results["dca"].get("simulations", []):
222 if (
223 sim.get("implementation") == "3-share masked"
224 and sim.get("num_traces") == 10000
225 ):
226 measured_correlation = float(sim["correct_correlation"])
227 break
228 if measured_correlation is None:
229 raise RuntimeError(
230 "dca_simulation.json lacks the '3-share masked' @10000-trace entry "
231 "that concrete_security_bounds.py requires; regenerate it."
232 )
233
234 # Footprints: derived from the measured base tables plus encoding sublayer (or raise).
235 table_bytes_A, table_bytes_B = load_measured_footprints(results_dir)
236
237 # 1. DCA resistance
238 print("-" * 70)
239 print("1. DCA (Differential Computation Analysis) RESISTANCE")
240 print("-" * 70)
241
242 dca_results = calculate_dca_security_bits(
243 num_traces=10000, measured_correlation=measured_correlation, num_shares=3
244 )
245
246 print(" Masking shares: 3")
247 print(f" Measured correlation (rho): {dca_results['measured_correlation']:.6f}")
248 print(
249 f" Sampling-noise floor (1/sqrt N): {dca_results['sampling_noise_floor']:.5f} (rho below floor: {dca_results['rho_below_floor']})"
250 )
251 print(
252 f" Traces for first-order (1/rho^2): {dca_results['traces_for_first_order']}"
253 )
254 print(
255 f" First-order estimate: ~2^{dca_results['first_order_bits']} traces (rho at face value)"
256 )
257 print(
258 f" Non-detection lower bound: >= 2^{dca_results['non_detection_floor_bits']} traces"
259 )
260 print(
261 f" >> REPORTED (first-order estimate, not a proof): {dca_results['security_level']}"
262 )
263 print()
264
265 # 2. Core table footprint (a size, NOT extraction resistance: the core is
266 # regenerable from |s_hat| at entry-determinacy degree 1).
267 print("-" * 70)
268 print("2. CORE TABLE FOOTPRINT (engineering size, not a security bound)")
269 print("-" * 70)
270
271 space_results_A = calculate_table_footprint(table_bytes_A)
272 space_results_B = calculate_table_footprint(table_bytes_B)
273
274 print(
275 f" Construction A (shared) : {space_results_A['table_size_bytes']:,} B = {space_results_A['table_size_mb']} MB -> {space_results_A['footprint_magnitude']}"
276 )
277 print(
278 f" Construction B (baked) : {space_results_B['table_size_bytes']:,} B = {space_results_B['table_size_mb']} MB -> {space_results_B['footprint_magnitude']}"
279 )
280 print(
281 " A size, not a security bound: the core is regenerable from |s_hat| (entry-determinacy degree 1)."
282 )
283 print()
284
285 # 3. Timing immunity -- structural, not a measured CoV/bit figure.
286 print("-" * 70)
287 print("3. TIMING IMMUNITY (Side-Channel Resistance)")
288 print("-" * 70)
289
290 timing_results = {
291 "model": "structural constant-time",
292 "basis": "table lookups; no secret-dependent branch or variable-latency arithmetic "
293 "(Freedom-from-Division-Timing-Leakage theorem, Section 4.5)",
294 "cov_bit_security_claimed": False,
295 "cache_line_constant_time": "not claimed",
296 }
297 print(
298 " Timing immunity is structural: constant-time table lookups with no secret-"
299 )
300 print(
301 " dependent branch or variable-latency arithmetic. No coefficient-of-variation"
302 )
303 print(" or bit-security figure is measured or claimed for ML-KEM in this work.")
304 print()
305
306 # Summary table
307 print("=" * 70)
308 print("SUMMARY: ENGINEERING SECURITY ESTIMATES (not proven bit-security)")
309 print("=" * 70)
310 print()
311 print("| Property | Measured Value | Estimate |")
312 print("|----------------------|-----------------------|--------------|")
313 print(
314 f"| DCA resistance | rho = {measured_correlation:.4f} | ~2^{int(dca_results['combined_security_bits'])} est. |"
315 )
316 print(
317 f"| Core footprint (A/B) | {space_results_A['table_size_mb']:.1f}/{space_results_B['table_size_mb']:.1f} MB tables | ~2^{space_results_A['byte_reads_to_copy_core_log2']}/2^{space_results_B['byte_reads_to_copy_core_log2']} size |"
318 )
319 print("| Timing (const-time) | no secret branches | structural |")
320 print()
321
322 print("Manuscript stance (open-problems section):")
323 print(
324 f" - DCA resistance: ~2^{int(dca_results['combined_security_bits'])} first-order trace-complexity estimate (1/rho^2, rho near the 10^4-trace noise floor); non-detection certifies >= 2^{int(dca_results['non_detection_floor_bits'])}; not a security proof"
325 )
326 print(
327 f" - Core footprint: ~2^{space_results_A['byte_reads_to_copy_core_log2']} (A, {space_results_A['table_size_mb']:.2f} MB) / ~2^{space_results_B['byte_reads_to_copy_core_log2']} (B, {space_results_B['table_size_mb']:.2f} MB) byte-reads to COPY the core -- an\n engineering size with no security content: the core has entry-determinacy degree 1, so it is\n regenerable from |s_hat| without reading it (results/table_extraction_witness.json)"
328 )
329 print(
330 " - Timing: structural constant-time construction (no secret-dependent branches); cache-line constant-time not claimed"
331 )
332 print()
333
334 output = {
335 "ml_kem_768_params": ML_KEM_768_PARAMS,
336 "whitebox_params": WB_PARAMS,
337 "experimental_inputs": {
338 "dca": {
339 "num_traces": 10000,
340 "measured_correlation": measured_correlation,
341 "source": "dca_simulation.json (3-share masked, 10000 traces)",
342 },
343 "space": {
344 "table_size_bytes_A_shared": table_bytes_A,
345 "table_size_bytes_B_baked": table_bytes_B,
346 "source": "whitebox_reference.json base tables + whitebox_encoded.json 3.41 MB encoding sublayer",
347 },
348 "timing": {
349 "model": "structural constant-time (no measured CoV; see timing_immunity)"
350 },
351 },
352 "security_bounds": {
353 "dca_resistance": dca_results,
354 "core_footprint_A_shared": space_results_A,
355 "core_footprint_B_baked": space_results_B,
356 "timing_immunity": timing_results,
357 },
358 "calculated_for_paper": {
359 "target_section": "Open Problems and Future Work",
360 "dca_security_bits": int(dca_results["combined_security_bits"]),
361 "core_byte_reads_log2_A_shared": (
362 space_results_A["byte_reads_to_copy_core_log2"]
363 ),
364 "core_byte_reads_log2_B_baked": (
365 space_results_B["byte_reads_to_copy_core_log2"]
366 ),
367 "core_footprint_is_security_bound": False,
368 },
369 }
370
371 os.makedirs(results_dir, exist_ok=True)
372 output_file = os.path.join(results_dir, "concrete_security_bounds.json")
373
374 with open(output_file, "w") as f:
375 json.dump(output, f, indent=2)
376
377 print(f"Results saved to: {output_file}")
378 print()
379 print("=" * 70)
380 print("VERIFICATION COMPLETE")
381 print("=" * 70)
382
383 return output
384
385
386if __name__ == "__main__":
387 main()
tuple load_measured_footprints(str results_dir)
Derive the two construction footprints from the committed measurements.
Dict[str, Any] load_experimental_results(str results_dir)
Load DCA and overhead JSON results if present.
main()
Compute all bounds, print the summary, and write the JSON output.
Dict[str, Any] calculate_table_footprint(int table_size_bytes)
Byte-read footprint of the protected core, as an engineering magnitude.
Dict[str, Any] calculate_dca_security_bits(int num_traces, float measured_correlation, int num_shares)
DCA security in bits from measured correlation.