From d5f840df657a7cf6f829403ca1c3b78e9d33da25 Mon Sep 17 00:00:00 2001 From: Sam Hadow Date: Tue, 5 May 2026 13:44:41 +0200 Subject: [PATCH] black box linear bias --- pyproject.toml | 2 ++ src/tea3/tea3linearbias.py | 66 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 src/tea3/tea3linearbias.py diff --git a/pyproject.toml b/pyproject.toml index 23b1449..60a7a8d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,3 +8,5 @@ requires-python = ">=3.11" [tool.pytest.ini_options] testpaths = ["tests"] +[project.scripts] +tea3-linear-bias = "tea3.tea3linearbias:main" diff --git a/src/tea3/tea3linearbias.py b/src/tea3/tea3linearbias.py new file mode 100644 index 0000000..c599989 --- /dev/null +++ b/src/tea3/tea3linearbias.py @@ -0,0 +1,66 @@ +from __future__ import annotations + +from dataclasses import dataclass +from random import Random + +from .tea3 import Tea3 + +def rand_key(rng: Random) -> list[int]: + return [rng.getrandbits(8) for _ in range(10)] + +@dataclass +class BiasResult: + samples: int + matches: int + p_match: float + bias: float + estimated_needed_samples: float + +def estimate_black_box_output_bias( + *, + frame_number: int, + output_byte_index: int = 0, + output_bit: int = 0, + samples: int = 10000, + seed: int = 1, +) -> BiasResult: + rng = Random(seed) + matches = 0 + + for _ in range(samples): + key = rand_key(rng) + tea = Tea3(frame_number, key) + + out_byte = 0 + for _ in range(output_byte_index + 1): + tea.next_byte() + out_byte = tea.iv_view() >> 56 + + bit = (out_byte >> output_bit) & 1 + if bit == 0: + matches += 1 + + p_match = matches / samples + bias = abs(p_match - 0.5) + needed = float("inf") if bias == 0 else 1.0 / (bias * bias) + + return BiasResult( + samples=samples, + matches=matches, + p_match=p_match, + bias=bias, + estimated_needed_samples=needed, + ) + +def main(): + frame = 0x12345678 + + res = estimate_black_box_output_bias( + frame_number=frame, + output_byte_index=0, + output_bit=0, + samples=20000, + seed=123, + ) + print("black-box output bias") + print(res)