3@file whitebox_encoded.py
4@brief Secret nonlinear I/O encoding layer over the base multiplication on the
5real NTT-domain secret; measures it against the NTT-linearity algebraic attack.
8@details Per NTT component i, two secret random bijections E_{i,0}, E_{i,1}:
9Z_q -> Z_q encode the two output coordinates of the base multiply
10p0 = shat0*c0 + gamma_i*shat1*c1, p1 = shat0*c1 + shat1*c0, where the stored
11secret shat = NTT(s) is full-range over Z_q. The plain product is computed
12internally and the encoded pair is emitted; the next pipeline stage decodes with
13the matching inverse. The encoding acts on the (full-range) output coordinates,
14so its footprint is independent of the base-table construction (see
15whitebox_reference.py for constructions A and B).
16@note MEASURED: encoded outputs defeat the plain linear-solve attack (encoding-
17unaware, mixing-aware) plus the encoding-table storage cost.
18@note CONDITIONAL/OPEN: security holds only if the secret encodings resist
19structural cryptanalysis. For AES this class of assumption was falsified by the
20Billet-Gilbert-Ech-Chatbi (BGE) attack; the lattice/NTT analogue is open. This is
21an empirical negative result for the tested attacker, not a proof of security.
22@note Deterministic (seed 42); writes results/whitebox_encoded.json.
24@section whitebox_encoded_output Output Files
25- `results/whitebox_encoded.json` - Encoded base multiply, self-test, attack
27@section whitebox_encoded_usage Usage
29python whitebox_encoded.py
34This software is provided for academic and research purposes.
35See LICENSE file for details.
44NUM_COMPONENTS = N // 2
51 @brief Powers of zeta mod q
for the NTT.
52 @return Array of 256 zeta powers.
54 z = np.zeros(256, dtype=np.int64)
56 for i
in range(1, 256):
57 z[i] = (z[i - 1] * ZETA) % Q
66 @brief Bit-reversal of a 7-bit index (FIPS-203 NTT twiddle order).
67 @param k Index
in [0, 128).
68 @return Bit-reversed 7-bit index.
70 return int(format(k & 0x7F,
"07b")[::-1], 2)
73GAMMAS = [pow(ZETA, 2 *
_bitrev7(i) + 1, Q)
for i
in range(NUM_COMPONENTS)]
78 @brief Forward NTT: coefficient domain to NTT domain (full-range image).
79 @param poly Length-256 coefficient vector.
80 @return NTT-domain coefficient vector.
82 r = 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 * r[j + length]) % Q
90 r[j + length] = (r[j] - t) % Q
96def build_encodings(rng):
98 @brief Secret nonlinear I/O encodings: two random bijections on Z_q per
99 component plus their inverses.
100 @param rng Seeded NumPy generator.
101 @return (E, Einv) forward
and inverse permutation tables.
103 E = np.empty((NUM_COMPONENTS, 2, Q), dtype=np.uint16)
104 Einv = np.empty((NUM_COMPONENTS, 2, Q), dtype=np.uint16)
105 for i
in range(NUM_COMPONENTS):
107 perm = rng.permutation(Q).astype(np.uint16)
109 inv = np.empty(Q, dtype=np.uint16)
110 inv[perm.astype(np.int64)] = np.arange(Q, dtype=np.uint16)
115def base_mul_direct(s0, s1, c0, c1, gamma):
117 @brief Base multiply
for one degree-2 factor
from full-range operands.
118 @param s0 s1 Full-range NTT-domain secret coordinates.
119 @param c0 c1 Ciphertext coordinates;
@param gamma Component twiddle.
120 @return (p0, p1) product pair mod q.
122 p0 = ((s0 * c0) + gamma * (s1 * c1)) % Q
123 p1 = ((s0 * c1) + (s1 * c0)) % Q
129 @brief Encoded output E_{i,0}(p0), E_{i,1}(p1) of the plain product.
130 @return Encoded (o0, o1) pair.
132 p0, p1 = base_mul_direct(s0, s1, c0, c1, gamma)
133 return int(E[i, 0, p0]), int(E[i, 1, p1])
138 @brief Recover full-range (s0,s1)
for one component
from chosen-ciphertext
139 observations by linear solve over Z_q.
140 @param observations List of (c0,c1,o0,o1) tuples.
141 @param gamma Component twiddle constant.
142 @param encoding_inverse Optional (inv0,inv1) tables; decodes outputs first.
143 @return (s0,s1)
or None.
144 @details Relation
is linear
in (s0,s1): o0 = s0*c0 + gamma*s1*c1,
145 o1 = s0*c1 + s1*c0; queries are stacked into the system.
148 for c0, c1, o0, o1
in observations:
149 if encoding_inverse
is not None:
150 o0 = int(encoding_inverse[0][o0])
151 o1 = int(encoding_inverse[1][o1])
152 rows.append((c0 % Q, (gamma * c1) % Q))
154 rows.append((c1 % Q, c0 % Q))
161 @brief Solve the over-determined linear system rows*x = rhs mod Q
for x
in Z_q^2.
162 @return (x0, x1)
or None if under-determined.
164 m = [[a % Q for a
in row] + [b % Q]
for row, b
in zip(rows, rhs)]
167 for col
in range(ncols):
169 for r
in range(pivot_row, len(m)):
170 if m[r][col] % Q != 0:
175 m[pivot_row], m[piv] = m[piv], m[pivot_row]
176 inv = pow(m[pivot_row][col], Q - 2, Q)
177 m[pivot_row] = [(v * inv) % Q
for v
in m[pivot_row]]
178 for r
in range(len(m)):
179 if r != pivot_row
and m[r][col] % Q != 0:
181 m[r] = [(m[r][k] - f * m[pivot_row][k]) % Q
for k
in range(ncols + 1)]
185 for r
in range(len(m)):
186 lead = next((c
for c
in range(ncols)
if m[r][c] % Q != 0),
None)
188 x[lead] = m[r][ncols] % Q
197 @brief Build encodings over the real full-range secret, verify decode
198 correctness, measure encoding footprint, run the algebraic attack.
200 rng = np.random.default_rng(SEED)
202 s_poly = rng.integers(-2, 3, size=N) % Q
203 shat = ntt_forward(s_poly) % Q
204 E, Einv = build_encodings(rng)
209 for _
in range(trials):
210 i = int(rng.integers(0, NUM_COMPONENTS))
211 s0, s1 = int(shat[2 * i]), int(shat[2 * i + 1])
212 c0 = int(rng.integers(0, Q))
213 c1 = int(rng.integers(0, Q))
215 d0 = int(Einv[i, 0, e0])
216 d1 = int(Einv[i, 1, e1])
217 pd = base_mul_direct(s0, s1, c0, c1, GAMMAS[i])
221 assert ok,
"CORRECTNESS FAILED: decoded encoded product != direct product"
224 enc_bytes = E.tobytes().__len__() + Einv.tobytes().__len__()
225 bits_per_encoding = int(np.ceil(np.log2(Q)))
226 entropy_bits_per_encoding = float(np.sum(np.log2(np.arange(1, Q + 1))))
232 rec_plain = rec_unaware = rec_aware = 0
233 for i
in range(NUM_COMPONENTS):
234 s0, s1 = int(shat[2 * i]), int(shat[2 * i + 1])
235 obs_plain, obs_enc = [], []
237 c0 = int(rng.integers(1, Q))
238 c1 = int(rng.integers(1, Q))
239 p0, p1 = base_mul_direct(s0, s1, c0, c1, GAMMAS[i])
240 obs_plain.append((c0, c1, p0, p1))
241 obs_enc.append((c0, c1, int(E[i, 0, p0]), int(E[i, 1, p1])))
249 obs_enc, GAMMAS[i], encoding_inverse=(Einv[i, 0], Einv[i, 1])
257 "num_components": NUM_COMPONENTS,
259 "ntt_domain_operand":
"shat = NTT(s), full-range over Z_q",
260 "shat_range": [int(shat.min()), int(shat.max())],
262 "correctness_trials": trials,
263 "correctness_passed":
True,
265 "scheme":
"per-component secret nonlinear bijection on Z_q for each of the two "
266 "output coordinates (128 x 2 encodings + inverses)",
267 "num_encodings": NUM_COMPONENTS * 2,
268 "storage_bits_per_encoding": bits_per_encoding * Q,
269 "key_entropy_bits_per_encoding_log2_qfact": round(
270 entropy_bits_per_encoding, 1
272 "basis":
"measured (encodings built and serialized)",
275 "encoding_tables_bytes": enc_bytes,
276 "encoding_tables_MB": round(enc_bytes / 1e6, 2),
277 "note":
"encoding tables store the 256 secret bijections and their inverses as "
278 "uint16 arrays; this is a MEASURED lower bound on the encoding-layer footprint. "
279 "It acts on the full-range output coordinates and is independent of the base-table "
280 "construction (A shared / B baked; see whitebox_reference.py).",
282 "algebraic_attack": {
283 "components_tested": NUM_COMPONENTS,
284 "queries_per_component": 3,
285 "recovery_plain_unencoded": rec_plain,
286 "recovery_encoded_encoding_unaware": rec_unaware,
287 "recovery_encoded_encoding_aware": rec_aware,
288 "interpretation":
"On the full-range NTT-domain secret, the plain linear-solve "
289 "recovers (shat0,shat1) from unencoded intermediates and from encoded "
290 "intermediates ONLY when the secret encoding is known; against the "
291 "encoding-unaware (mixing-aware) attacker it fails. This is an EMPIRICAL "
292 "NEGATIVE result for the tested attacker, not a proof: a structural "
293 "attacker that recovers the encodings (BGE-style, open for the lattice "
294 "setting) is not modelled here.",
297 script_dir = os.path.dirname(os.path.abspath(__file__))
298 results_dir = os.path.join(os.path.dirname(os.path.dirname(script_dir)),
"results")
299 os.makedirs(results_dir, exist_ok=
True)
300 output_file = os.path.join(results_dir,
"whitebox_encoded.json")
301 with open(output_file,
"w", encoding=
"utf-8", newline=
"\n")
as f:
302 json.dump(out, f, indent=2)
304 "CORRECTNESS: PASSED (%d trials, all components; decode(encode(p))==direct, full-range secret)"
307 print(
"shat range: [%d, %d]" % (int(shat.min()), int(shat.max())))
308 print(
"ENCODING storage (measured): %.2f MB" % out[
"storage"][
"encoding_tables_MB"])
310 "ENCODING key entropy: log2(q!) ~= %.0f bits per bijection (%d encodings)"
311 % (entropy_bits_per_encoding, NUM_COMPONENTS * 2)
314 "ALGEBRAIC ATTACK recovery over %d components (3 queries each):"
317 print(
" plain unencoded : %d/%d" % (rec_plain, NUM_COMPONENTS))
319 " encoded, encoding-UNAWARE : %d/%d (mixing-aware attacker fails)"
320 % (rec_unaware, NUM_COMPONENTS)
323 " encoded, encoding-AWARE : %d/%d (sanity: encoding is the only barrier)"
324 % (rec_aware, NUM_COMPONENTS)
328if __name__ ==
"__main__":
main()
Build encodings over the real full-range secret, verify decode correctness, measure encoding footprin...
solve_component(observations, gamma, encoding_inverse=None)
Recover full-range (s0,s1) for one component from chosen-ciphertext observations by linear solve over...
_bitrev7(k)
Bit-reversal of a 7-bit index (FIPS-203 NTT twiddle order).
base_mul_encoded(s0, s1, c0, c1, gamma, E, i)
Encoded output E_{i,0}(p0), E_{i,1}(p1) of the plain product.
_zeta_powers()
Powers of zeta mod q for the NTT.
_gauss_solve_modq(rows, rhs)
Solve the over-determined linear system rows*x = rhs mod Q for x in Z_q^2.