modularot 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- modularot/__init__.py +49 -0
- modularot/cli.py +381 -0
- modularot/custom_kems/__init__.py +0 -0
- modularot/custom_kems/ggh_fo/__init__.py +0 -0
- modularot/custom_kems/ggh_fo/ggh_fo.py +280 -0
- modularot/custom_kems/ntru_fo/__init__.py +0 -0
- modularot/custom_kems/ntru_fo/ntru_fo.py +347 -0
- modularot/kem_adapter/__init__.py +0 -0
- modularot/kem_adapter/adapter.py +58 -0
- modularot/oblivious_sampling.py +207 -0
- modularot/ot_protocol.py +332 -0
- modularot-0.1.0.dist-info/METADATA +63 -0
- modularot-0.1.0.dist-info/RECORD +17 -0
- modularot-0.1.0.dist-info/WHEEL +5 -0
- modularot-0.1.0.dist-info/entry_points.txt +2 -0
- modularot-0.1.0.dist-info/licenses/LICENSE +21 -0
- modularot-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Oblivious public-key sampling for the KEM-based OT (semi-honest, lattice KEMs).
|
|
3
|
+
|
|
4
|
+
This is the only KEM-aware module; the protocol in ot_protocol.py just calls
|
|
5
|
+
the sampler returned here.
|
|
6
|
+
|
|
7
|
+
An oblivious public key is a well-formed pk, distributed like a real one, whose
|
|
8
|
+
secret key nobody knows. The receiver supplies it for the non-chosen branch, so
|
|
9
|
+
the sender's shared secret there is pseudorandom to the receiver.
|
|
10
|
+
|
|
11
|
+
Requirements on a sampler:
|
|
12
|
+
* sender privacy: nobody knows the secret key (no sampler runs KeyGen).
|
|
13
|
+
* receiver privacy: real and oblivious pks must be indistinguishable, so the
|
|
14
|
+
bytes must decode to the same coefficient distribution, in the same
|
|
15
|
+
encoding. This rests on each scheme's decisional assumption (M-LWE, LWE,
|
|
16
|
+
NTRU, NTRU Prime).
|
|
17
|
+
|
|
18
|
+
Sampling cannot be black-box over an arbitrary KEM (Gertner et al., FOCS 2000),
|
|
19
|
+
so each family has its own sampler; encodings were verified against liboqs
|
|
20
|
+
(Encode(Decode(real_pk)) == real_pk).
|
|
21
|
+
|
|
22
|
+
Coverage:
|
|
23
|
+
* ML-KEM-{512,768,1024}, Kyber{512,768,1024} -> q=3329 ByteEncode_12
|
|
24
|
+
* FrodoKEM / eFrodoKEM -> uniform bytes
|
|
25
|
+
* NTRU-HPS / NTRU-HRSS -> bit-packed n-1 coefficients
|
|
26
|
+
* sntrup761 -> NTRU Prime Encode, q prime
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
import secrets
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# ── structured lattice, prime modulus q = 3329 (ML-KEM, Kyber) ────────────────
|
|
33
|
+
|
|
34
|
+
_Q3329 = 3329
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _byte_encode_12(coeffs):
|
|
38
|
+
"""FIPS 203 ByteEncode_12: two 12-bit coefficients per three bytes."""
|
|
39
|
+
out = bytearray()
|
|
40
|
+
for i in range(0, len(coeffs), 2):
|
|
41
|
+
d0, d1 = coeffs[i], coeffs[i + 1]
|
|
42
|
+
out.append(d0 & 0xFF)
|
|
43
|
+
out.append(((d0 >> 8) & 0x0F) | ((d1 & 0x0F) << 4))
|
|
44
|
+
out.append((d1 >> 4) & 0xFF)
|
|
45
|
+
return bytes(out)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def sample_oblivious_q3329(real_pk: bytes) -> bytes:
|
|
49
|
+
"""pk = ByteEncode_12(t) || rho, with t uniform in [0, q) (M-LWE) and a
|
|
50
|
+
fresh seed rho. `real_pk` only gives the length, hence k."""
|
|
51
|
+
if (len(real_pk) - 32) % 384 != 0:
|
|
52
|
+
raise ValueError("not a q=3329 lattice public-key length")
|
|
53
|
+
k = (len(real_pk) - 32) // 384
|
|
54
|
+
coeffs = [secrets.randbelow(_Q3329) for _ in range(256 * k)]
|
|
55
|
+
return _byte_encode_12(coeffs) + secrets.token_bytes(32)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# ── uniform bytes (LWE, power-of-two modulus) ─────────────────────────────────
|
|
59
|
+
|
|
60
|
+
def sample_oblivious_uniform_bytes(real_pk: bytes) -> bytes:
|
|
61
|
+
"""FrodoKEM: the pk is uniform under decisional LWE and has no range or
|
|
62
|
+
padding constraint."""
|
|
63
|
+
return secrets.token_bytes(len(real_pk))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# ── bit-packed n-1 coefficients, power-of-two modulus (NTRU-HPS / NTRU-HRSS) ──
|
|
67
|
+
#
|
|
68
|
+
# pk = h packed as (n-1) coefficients of log2(q) bits. Every bit pattern is a
|
|
69
|
+
# valid coefficient, so the sampler is uniform bytes with bits >= sig_bits
|
|
70
|
+
# zeroed. sig_bits == (n-1)*log2(q), verified against liboqs.
|
|
71
|
+
_NTRU_BITPACK = {
|
|
72
|
+
"NTRU-HPS-2048-509": 5588,
|
|
73
|
+
"NTRU-HPS-2048-677": 7436,
|
|
74
|
+
"NTRU-HPS-4096-821": 9840,
|
|
75
|
+
"NTRU-HPS-4096-1229": 14736,
|
|
76
|
+
"NTRU-HRSS-701": 9100,
|
|
77
|
+
"NTRU-HRSS-1373": 19208,
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _make_bitpacked_sampler(sig_bits: int):
|
|
82
|
+
def sampler(real_pk: bytes) -> bytes:
|
|
83
|
+
out = bytearray(secrets.token_bytes(len(real_pk)))
|
|
84
|
+
full, rem = sig_bits // 8, sig_bits % 8
|
|
85
|
+
if rem:
|
|
86
|
+
out[full] &= 0xFF >> (8 - rem) # keep low `rem` bits
|
|
87
|
+
full += 1
|
|
88
|
+
for i in range(full, len(out)):
|
|
89
|
+
out[i] = 0 # zero padding
|
|
90
|
+
return bytes(out)
|
|
91
|
+
return sampler
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# ── NTRU Prime Encode of uniform coefficients (sntrup) ────────────────────────
|
|
95
|
+
#
|
|
96
|
+
# Uniform bytes do not decode to uniform in-range coefficients, so sample
|
|
97
|
+
# p coefficients in [0, q) and apply the mixed-radix Encode (matches liboqs).
|
|
98
|
+
_SNTRUP = {"sntrup761": (761, 4591)}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _ntruprime_encode(R, M):
|
|
102
|
+
if len(M) == 0:
|
|
103
|
+
return []
|
|
104
|
+
S = []
|
|
105
|
+
if len(M) == 1:
|
|
106
|
+
r, m = R[0], M[0]
|
|
107
|
+
while m > 1:
|
|
108
|
+
S += [r % 256]
|
|
109
|
+
r, m = r // 256, (m + 255) // 256
|
|
110
|
+
return S
|
|
111
|
+
R2, M2 = [], []
|
|
112
|
+
for i in range(0, len(M) - 1, 2):
|
|
113
|
+
m, r = M[i] * M[i + 1], R[i] + R[i + 1] * M[i]
|
|
114
|
+
while m >= 16384:
|
|
115
|
+
S += [r % 256]
|
|
116
|
+
r, m = r // 256, (m + 255) // 256
|
|
117
|
+
R2 += [r]
|
|
118
|
+
M2 += [m]
|
|
119
|
+
if len(M) & 1:
|
|
120
|
+
R2 += [R[-1]]
|
|
121
|
+
M2 += [M[-1]]
|
|
122
|
+
return S + _ntruprime_encode(R2, M2)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _make_ntruprime_sampler(p: int, q: int):
|
|
126
|
+
M = [q] * p
|
|
127
|
+
|
|
128
|
+
def sampler(real_pk: bytes) -> bytes:
|
|
129
|
+
return bytes(_ntruprime_encode([secrets.randbelow(q) for _ in range(p)], M))
|
|
130
|
+
return sampler
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
# ── NTRU_FO (custom, research-grade, N=701/p=3/q=8192 by default) ────────────
|
|
134
|
+
#
|
|
135
|
+
# Ring x^N - 1: pk = h = p*g*f^{-1} mod q, as N coefficients in [0, q), each
|
|
136
|
+
# in a 4-byte big-endian field (NTRU_FO._poly_to_bytes). Uniform bytes would set
|
|
137
|
+
# the high bits and be distinguishable, so sample each coefficient in [0, q).
|
|
138
|
+
# q is not recoverable from the key length and must match the instance.
|
|
139
|
+
|
|
140
|
+
def sample_oblivious_ntru_fo(real_pk: bytes, q: int = 8192) -> bytes:
|
|
141
|
+
"""Oblivious NTRU_FO public key; `q` must match the instance's modulus."""
|
|
142
|
+
if len(real_pk) % 4 != 0:
|
|
143
|
+
raise ValueError("not a 4-byte-per-coefficient NTRU_FO public key")
|
|
144
|
+
n = len(real_pk) // 4
|
|
145
|
+
return b"".join(secrets.randbelow(q).to_bytes(4, "big") for _ in range(n))
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# ── GGH-HNF (custom library) ─────────────────────────────────────────────────
|
|
149
|
+
#
|
|
150
|
+
# Classic GGH (pk = basis B = U·R) is refused: det B, entry marginals and row
|
|
151
|
+
# norms separate real keys from any trapdoor-free sample, and no
|
|
152
|
+
# pseudorandomness assumption exists.
|
|
153
|
+
#
|
|
154
|
+
# The HNF variant (ggh_fo, GGH_private=True) publishes HNF(L), a canonical form
|
|
155
|
+
# revealing only det, the cokernel (HNF diagonal) and reduced column entries.
|
|
156
|
+
# Sampler ("discarded draw"):
|
|
157
|
+
# 1. draw once from the keygen law and keep only diag(HNF(R'')); R'' is
|
|
158
|
+
# discarded, so nobody holds a short basis of the output;
|
|
159
|
+
# 2. fill the reduced entries (rows k < i of columns with d_i > 1)
|
|
160
|
+
# uniformly in [0, d_i); columns with d_i = 1 are zero in any HNF.
|
|
161
|
+
# Indistinguishability rests on a planted-short-basis (uSVP-style) decisional
|
|
162
|
+
# assumption: unproven, but not known to be false.
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def sample_oblivious_ggh_hnf(real_pk: bytes) -> bytes:
|
|
166
|
+
"""Oblivious GGH-HNF public key. Only the dimension header of `real_pk`
|
|
167
|
+
is used; reusing its diagonal would correlate det/cokernel across branches."""
|
|
168
|
+
# lazy import: flint/GGH_crypto are an optional extra
|
|
169
|
+
import struct
|
|
170
|
+
from .custom_kems.ggh_fo import ggh_fo
|
|
171
|
+
|
|
172
|
+
(n,) = struct.unpack_from(">i", real_pk, 0)
|
|
173
|
+
diag = ggh_fo.draw_lattice_diag(n) # discarded draw
|
|
174
|
+
cols = {
|
|
175
|
+
i: [secrets.randbelow(diag[i]) for _ in range(i)]
|
|
176
|
+
for i in range(n) if diag[i] > 1
|
|
177
|
+
}
|
|
178
|
+
return ggh_fo._ser_pk(n, diag, cols)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
# ── dispatch ─────────────────────────────────────────────────────────────────
|
|
182
|
+
|
|
183
|
+
def resolve_oqs(alg: str):
|
|
184
|
+
"""Return `real_pk -> oblivious_pk` for a liboqs mechanism, or raise
|
|
185
|
+
NotImplementedError if there is no sampler."""
|
|
186
|
+
if alg.startswith("ML-KEM") or alg.startswith("Kyber"):
|
|
187
|
+
return sample_oblivious_q3329
|
|
188
|
+
if alg.startswith("FrodoKEM") or alg.startswith("eFrodoKEM"):
|
|
189
|
+
return sample_oblivious_uniform_bytes
|
|
190
|
+
if alg in _NTRU_BITPACK:
|
|
191
|
+
return _make_bitpacked_sampler(_NTRU_BITPACK[alg])
|
|
192
|
+
if alg in _SNTRUP:
|
|
193
|
+
return _make_ntruprime_sampler(*_SNTRUP[alg])
|
|
194
|
+
if alg.startswith("ntrulpr"):
|
|
195
|
+
raise NotImplementedError(
|
|
196
|
+
f"{alg}: NTRU Prime LPR uses the Rounded encoding (different moduli "
|
|
197
|
+
"per limb); needs its own Encode wiring."
|
|
198
|
+
)
|
|
199
|
+
raise NotImplementedError(f"{alg!r}: no oblivious sampler")
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def is_supported_oqs(alg: str) -> bool:
|
|
203
|
+
try:
|
|
204
|
+
resolve_oqs(alg)
|
|
205
|
+
return True
|
|
206
|
+
except NotImplementedError:
|
|
207
|
+
return False
|
modularot/ot_protocol.py
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Modular KEM-based 1-out-of-n Oblivious Transfer (semi-honest secure).
|
|
3
|
+
|
|
4
|
+
Construction:
|
|
5
|
+
1. Receiver(b) generates a real keypair for branch b and an oblivious
|
|
6
|
+
public key (no one knows its secret key) for every other branch, and
|
|
7
|
+
sends all n public keys.
|
|
8
|
+
2. Sender encapsulates under each public key, AEAD-seals m_i with the
|
|
9
|
+
shared secret, and sends all n ciphertexts and sealed blobs.
|
|
10
|
+
3. Receiver decapsulates ct_b with sk_b and opens m_b. It has no secret
|
|
11
|
+
for the other keys, so m_{i!=b} stays hidden.
|
|
12
|
+
|
|
13
|
+
Security (semi-honest):
|
|
14
|
+
* Receiver privacy: the sender holds no secret key, so real and oblivious
|
|
15
|
+
pks are indistinguishable and b is hidden.
|
|
16
|
+
* Sender privacy: recovering ss_i without sk_i breaks the KEM (IND-CPA);
|
|
17
|
+
a union bound over the n-1 hidden branches covers the receiver's whole
|
|
18
|
+
view, since secrets for oblivious keys never exist.
|
|
19
|
+
|
|
20
|
+
Cost:
|
|
21
|
+
* Receiver: 1 KeyGen + (n-1) oblivious samples + 1 Decaps. The samplers
|
|
22
|
+
are pure Python, so they dominate for cheap-KeyGen KEMs (ML-KEM) and
|
|
23
|
+
KeyGen dominates for FrodoKEM and NTRU.
|
|
24
|
+
* Sender: n Encaps + n AEAD seals.
|
|
25
|
+
* Bandwidth: n public keys one way, n (ct + sealed blob) the other.
|
|
26
|
+
|
|
27
|
+
The only KEM-specific operation, oblivious pk sampling, is injected as a
|
|
28
|
+
callable from `oblivious_sampling`. A black-box KEM cannot yield a
|
|
29
|
+
sender-private OT (GKMRV, FOCS 2000).
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from typing import List, Optional, Callable
|
|
33
|
+
import secrets
|
|
34
|
+
import hashlib
|
|
35
|
+
import time
|
|
36
|
+
|
|
37
|
+
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
|
38
|
+
from cryptography.hazmat.primitives import hashes
|
|
39
|
+
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
|
|
40
|
+
|
|
41
|
+
from .kem_adapter.adapter import KEMAdapter
|
|
42
|
+
from .oblivious_sampling import resolve_oqs
|
|
43
|
+
import oqs
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _fmt_ns(ns: int) -> str:
|
|
47
|
+
if ns < 1_000:
|
|
48
|
+
return f"{ns} ns"
|
|
49
|
+
elif ns < 1_000_000:
|
|
50
|
+
return f"{ns / 1_000:.3f} µs"
|
|
51
|
+
elif ns < 1_000_000_000:
|
|
52
|
+
return f"{ns / 1_000_000:.3f} ms"
|
|
53
|
+
else:
|
|
54
|
+
return f"{ns / 1_000_000_000:.3f} s"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _print_step(label: str, ns: int) -> None:
|
|
58
|
+
print(f" {label:<48} {_fmt_ns(ns):>14}")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# ── key/nonce/AD derivation (binds session, branch, pk, label) ────────────────
|
|
62
|
+
|
|
63
|
+
def compute_pk_fingerprint(public_key: bytes) -> bytes:
|
|
64
|
+
return hashlib.sha256(public_key).digest()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def derive_key(shared_secret: bytes, session_id: bytes, branch: int, pk_fp: bytes) -> bytes:
|
|
68
|
+
info = (b"MODULAROT\x00session:" + session_id + b"\x00branch:"
|
|
69
|
+
+ str(branch).encode("ascii") + b"\x00pk:" + pk_fp)
|
|
70
|
+
return HKDF(algorithm=hashes.SHA256(), length=32, salt=session_id, info=info).derive(shared_secret)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def build_associated_data(session_id: bytes, branch: int, pk_fp: bytes, label: bytes) -> bytes:
|
|
74
|
+
return (b"MODULAROT||session:" + session_id + b"||branch:"
|
|
75
|
+
+ str(branch).encode("ascii") + b"||pk:" + pk_fp + b"||label:" + label)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def derive_nonce(shared_secret: bytes, session_id: bytes, branch: int, pk_fp: bytes, label: bytes) -> bytes:
|
|
79
|
+
info = (b"MODULAROT_nonce||session:" + session_id + b"||branch:"
|
|
80
|
+
+ str(branch).encode("ascii") + b"||pk:" + pk_fp + b"||label:" + label)
|
|
81
|
+
return HKDF(algorithm=hashes.SHA256(), length=12, salt=session_id, info=info).derive(shared_secret)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _label(branch: int) -> bytes:
|
|
85
|
+
return f"message_{branch}".encode("ascii")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
# ── OT parties ────────────────────────────────────────────────────────────────
|
|
89
|
+
|
|
90
|
+
class OTReceiver:
|
|
91
|
+
"""Holds the real keypair for the chosen branch only."""
|
|
92
|
+
|
|
93
|
+
def __init__(self, choice: int, kem: KEMAdapter,
|
|
94
|
+
sample_oblivious_pk: Callable[[bytes], bytes], n: int = 2):
|
|
95
|
+
if n < 2:
|
|
96
|
+
raise ValueError("Need at least 2 branches")
|
|
97
|
+
if not 0 <= choice < n:
|
|
98
|
+
raise ValueError(f"Choice must be in [0, {n - 1}]")
|
|
99
|
+
self.n = n
|
|
100
|
+
self.choice = choice
|
|
101
|
+
self.kem = kem
|
|
102
|
+
self.sample_oblivious_pk = sample_oblivious_pk
|
|
103
|
+
self._real_sk: Optional[bytes] = None
|
|
104
|
+
self._pk: List[Optional[bytes]] = [None] * n # pks as sent
|
|
105
|
+
|
|
106
|
+
def request(self) -> List[bytes]:
|
|
107
|
+
"""Return n public keys: real at `choice`, oblivious elsewhere."""
|
|
108
|
+
pk_real, self._real_sk = self.kem.Gen()
|
|
109
|
+
self._pk = [pk_real if i == self.choice else self.sample_oblivious_pk(pk_real)
|
|
110
|
+
for i in range(self.n)]
|
|
111
|
+
return list(self._pk)
|
|
112
|
+
|
|
113
|
+
def finalize(self, cts: List[bytes], sealeds: List[bytes],
|
|
114
|
+
session_id: bytes) -> Optional[bytes]:
|
|
115
|
+
b = self.choice
|
|
116
|
+
pk_fp = compute_pk_fingerprint(self._pk[b]) # recompute, don't trust sender
|
|
117
|
+
|
|
118
|
+
ss = self.kem.decaps(self._real_sk, cts[b])
|
|
119
|
+
key = derive_key(ss, session_id, b, pk_fp)
|
|
120
|
+
ad = build_associated_data(session_id, b, pk_fp, _label(b))
|
|
121
|
+
nonce = derive_nonce(ss, session_id, b, pk_fp, _label(b))
|
|
122
|
+
try:
|
|
123
|
+
return ChaCha20Poly1305(key).decrypt(nonce, sealeds[b], ad)
|
|
124
|
+
except Exception as e:
|
|
125
|
+
print(f"[Receiver] decryption failed: {e}")
|
|
126
|
+
return None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class OTSender:
|
|
130
|
+
"""Encapsulates under each received pk; cannot tell real from oblivious."""
|
|
131
|
+
|
|
132
|
+
def __init__(self, kem: KEMAdapter, messages: List[bytes]):
|
|
133
|
+
if len(messages) < 2:
|
|
134
|
+
raise ValueError("Need at least 2 messages")
|
|
135
|
+
self.kem = kem
|
|
136
|
+
self.messages = list(messages)
|
|
137
|
+
self.session_id = secrets.token_bytes(32)
|
|
138
|
+
|
|
139
|
+
def transfer(self, pks: List[bytes]):
|
|
140
|
+
if len(pks) != len(self.messages):
|
|
141
|
+
raise ValueError(f"Got {len(pks)} public keys for {len(self.messages)} messages")
|
|
142
|
+
cts, sealeds = [], []
|
|
143
|
+
for i, pk in enumerate(pks):
|
|
144
|
+
ss, ct = self.kem.encaps(pk)
|
|
145
|
+
cts.append(ct)
|
|
146
|
+
sealeds.append(self._seal(ss, i, pk, self.messages[i]))
|
|
147
|
+
return cts, sealeds, self.session_id
|
|
148
|
+
|
|
149
|
+
def _seal(self, ss: bytes, branch: int, pk: bytes, msg: bytes) -> bytes:
|
|
150
|
+
pk_fp = compute_pk_fingerprint(pk)
|
|
151
|
+
key = derive_key(ss, self.session_id, branch, pk_fp)
|
|
152
|
+
ad = build_associated_data(self.session_id, branch, pk_fp, _label(branch))
|
|
153
|
+
nonce = derive_nonce(ss, self.session_id, branch, pk_fp, _label(branch))
|
|
154
|
+
return ChaCha20Poly1305(key).encrypt(nonce, msg, ad)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
# ── check: a curious receiver must not recover any m_{i != b} ─────────────────
|
|
158
|
+
|
|
159
|
+
def receiver_cannot_read_other(make_kem, receiver: OTReceiver,
|
|
160
|
+
cts, sealeds, session_id) -> bool:
|
|
161
|
+
"""Try to open every m_{i != b} with the keys the receiver has (a forged
|
|
162
|
+
sk and its real sk_b), on fresh and on the receiver's own KEM instances.
|
|
163
|
+
Return True iff every AEAD open fails."""
|
|
164
|
+
_, forged_sk = make_kem().Gen()
|
|
165
|
+
attempts = [(make_kem(), forged_sk),
|
|
166
|
+
(make_kem(), receiver._real_sk),
|
|
167
|
+
(receiver.kem, receiver._real_sk)]
|
|
168
|
+
for other in range(receiver.n):
|
|
169
|
+
if other == receiver.choice:
|
|
170
|
+
continue
|
|
171
|
+
pk_fp = compute_pk_fingerprint(receiver._pk[other])
|
|
172
|
+
for kem, sk in attempts:
|
|
173
|
+
try:
|
|
174
|
+
ss_guess = kem.decaps(sk, cts[other])
|
|
175
|
+
except Exception:
|
|
176
|
+
continue # decaps refused
|
|
177
|
+
key = derive_key(ss_guess, session_id, other, pk_fp)
|
|
178
|
+
ad = build_associated_data(session_id, other, pk_fp, _label(other))
|
|
179
|
+
nonce = derive_nonce(ss_guess, session_id, other, pk_fp, _label(other))
|
|
180
|
+
try:
|
|
181
|
+
ChaCha20Poly1305(key).decrypt(nonce, sealeds[other], ad)
|
|
182
|
+
return False # sender privacy broken
|
|
183
|
+
except Exception:
|
|
184
|
+
continue
|
|
185
|
+
return True
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
# ── runner ────────────────────────────────────────────────────────────────────
|
|
189
|
+
|
|
190
|
+
def run_ot(make_kem: Callable[[], KEMAdapter],
|
|
191
|
+
sampler: Callable[[bytes], bytes],
|
|
192
|
+
label: str, choice: int = 0, n: int = 2,
|
|
193
|
+
messages: Optional[List[bytes]] = None,
|
|
194
|
+
check_security: bool = True, verbose: bool = True) -> dict:
|
|
195
|
+
if messages is None:
|
|
196
|
+
messages = [f"Secret message {i} [{label}]".encode() for i in range(n)]
|
|
197
|
+
elif len(messages) != n:
|
|
198
|
+
raise ValueError(f"Got {len(messages)} messages for n={n}")
|
|
199
|
+
|
|
200
|
+
total_start = time.perf_counter_ns()
|
|
201
|
+
|
|
202
|
+
t0 = time.perf_counter_ns()
|
|
203
|
+
receiver = OTReceiver(choice, make_kem(), sampler, n=n)
|
|
204
|
+
sender = OTSender(make_kem(), messages)
|
|
205
|
+
t_init = time.perf_counter_ns() - t0
|
|
206
|
+
|
|
207
|
+
# Receiver -> Sender : [pk_0..pk_{n-1}] [KeyGen x1 + oblivious sample x(n-1)]
|
|
208
|
+
t0 = time.perf_counter_ns()
|
|
209
|
+
pks = receiver.request()
|
|
210
|
+
t_request = time.perf_counter_ns() - t0
|
|
211
|
+
|
|
212
|
+
# Sender -> Receiver : ciphertexts + sealed messages [Encaps xn + AEAD xn]
|
|
213
|
+
t0 = time.perf_counter_ns()
|
|
214
|
+
cts, sealeds, session_id = sender.transfer(pks)
|
|
215
|
+
t_transfer = time.perf_counter_ns() - t0
|
|
216
|
+
|
|
217
|
+
# Receiver opens chosen message [Decaps x1 + AEAD open x1]
|
|
218
|
+
t0 = time.perf_counter_ns()
|
|
219
|
+
received = receiver.finalize(cts, sealeds, session_id)
|
|
220
|
+
t_finalize = time.perf_counter_ns() - t0
|
|
221
|
+
|
|
222
|
+
total_ns = time.perf_counter_ns() - total_start
|
|
223
|
+
|
|
224
|
+
ok = received == messages[choice]
|
|
225
|
+
secure = (receiver_cannot_read_other(make_kem, receiver, cts, sealeds, session_id)
|
|
226
|
+
if check_security else None)
|
|
227
|
+
|
|
228
|
+
pk_bw = sum(len(pk) for pk in pks)
|
|
229
|
+
ct_bw = sum(len(ct) for ct in cts) + sum(len(s) for s in sealeds)
|
|
230
|
+
|
|
231
|
+
if verbose:
|
|
232
|
+
print(f"\nKEM: {label} | 1-out-of-{n} | choice: {choice}")
|
|
233
|
+
print(f" {'─' * 64}")
|
|
234
|
+
_print_step("Init (Receiver + Sender)", t_init)
|
|
235
|
+
_print_step(f"Receiver.request (KeyGen x1 + obliv pk x{n - 1})", t_request)
|
|
236
|
+
_print_step(f"Sender.transfer (Encaps x{n} + AEAD seal x{n})", t_transfer)
|
|
237
|
+
_print_step("Receiver.finalize (Decaps x1 + AEAD open x1)", t_finalize)
|
|
238
|
+
print(f" {'─' * 64}")
|
|
239
|
+
_print_step("TOTAL", total_ns)
|
|
240
|
+
print()
|
|
241
|
+
print(f" Bandwidth R->S : {pk_bw} B ({n} public keys)")
|
|
242
|
+
print(f" Bandwidth S->R : {ct_bw} B ({n} ct + {n} sealed)")
|
|
243
|
+
print(f" Correct (gets m_b) : {ok}")
|
|
244
|
+
print(f" Decrypted message : {received!r}")
|
|
245
|
+
if check_security:
|
|
246
|
+
print(f" Sender-private : {secure} (receiver cannot read any m_(i!=b))")
|
|
247
|
+
|
|
248
|
+
return {"KEM": label, "n": n, "init": t_init, "request": t_request,
|
|
249
|
+
"transfer": t_transfer, "finalize": t_finalize, "TOTAL": total_ns,
|
|
250
|
+
"pk_bw": pk_bw, "ct_bw": ct_bw, "ok": ok, "secure": secure,
|
|
251
|
+
"message": received}
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _oqs_kem_factory(kemalg: str) -> Callable[[], KEMAdapter]:
|
|
255
|
+
def oqs_gen():
|
|
256
|
+
kem = oqs.KeyEncapsulation(kemalg)
|
|
257
|
+
pk = kem.generate_keypair()
|
|
258
|
+
sk = kem.export_secret_key()
|
|
259
|
+
kem.free()
|
|
260
|
+
return pk, sk
|
|
261
|
+
|
|
262
|
+
def oqs_encap(pk):
|
|
263
|
+
kem = oqs.KeyEncapsulation(kemalg)
|
|
264
|
+
ct, ss = kem.encap_secret(pk)
|
|
265
|
+
kem.free()
|
|
266
|
+
return ss, ct
|
|
267
|
+
|
|
268
|
+
def oqs_decap(sk, ct):
|
|
269
|
+
kem = oqs.KeyEncapsulation(kemalg, secret_key=sk)
|
|
270
|
+
ss = kem.decap_secret(ct)
|
|
271
|
+
kem.free()
|
|
272
|
+
return ss
|
|
273
|
+
|
|
274
|
+
return lambda: KEMAdapter(gen=oqs_gen, encap=oqs_encap, decap=oqs_decap)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def demo_oqs_ot():
|
|
278
|
+
print("=" * 72)
|
|
279
|
+
print("Modular OT over enabled lattice liboqs KEMs (semi-honest, sender-private)")
|
|
280
|
+
print("=" * 72)
|
|
281
|
+
|
|
282
|
+
results, skipped = [], []
|
|
283
|
+
for kemalg in oqs.get_enabled_kem_mechanisms():
|
|
284
|
+
try:
|
|
285
|
+
sampler = resolve_oqs(kemalg)
|
|
286
|
+
except NotImplementedError as e:
|
|
287
|
+
skipped.append((kemalg, str(e).split(":", 1)[-1].strip()))
|
|
288
|
+
continue
|
|
289
|
+
except KeyError:
|
|
290
|
+
continue # non-lattice: excluded
|
|
291
|
+
|
|
292
|
+
# warmup: keep liboqs lazy init out of the timings
|
|
293
|
+
_wu = oqs.KeyEncapsulation(kemalg)
|
|
294
|
+
_wu_pk = _wu.generate_keypair()
|
|
295
|
+
_wu_ct, _ = _wu.encap_secret(_wu_pk)
|
|
296
|
+
_wu.decap_secret(_wu_ct)
|
|
297
|
+
_wu.free()
|
|
298
|
+
|
|
299
|
+
results.append(run_ot(_oqs_kem_factory(kemalg), sampler, kemalg, choice=0))
|
|
300
|
+
|
|
301
|
+
kw = max((len(r["KEM"]) for r in results), default=14)
|
|
302
|
+
header = (f"{'KEM':<{kw}} {'Request':>12} {'Transfer':>12} {'Finalize':>12} "
|
|
303
|
+
f"{'TOTAL':>12} OK SEC")
|
|
304
|
+
print(f"\n\n{'═' * len(header)}")
|
|
305
|
+
print(f"BENCHMARK SUMMARY — {len(results)} supported / "
|
|
306
|
+
f"{len(results) + len(skipped)} enabled")
|
|
307
|
+
print(f"{'═' * len(header)}")
|
|
308
|
+
print(header)
|
|
309
|
+
print("─" * len(header))
|
|
310
|
+
for r in results:
|
|
311
|
+
print(f"{r['KEM']:<{kw}} {_fmt_ns(r['request']):>12} {_fmt_ns(r['transfer']):>12} "
|
|
312
|
+
f"{_fmt_ns(r['finalize']):>12} {_fmt_ns(r['TOTAL']):>12} "
|
|
313
|
+
f"{'✓' if r['ok'] else '✗'} {'✓' if r['secure'] else '✗'}")
|
|
314
|
+
print("─" * len(header))
|
|
315
|
+
if skipped:
|
|
316
|
+
print(f"\nNOT SUPPORTED ({len(skipped)}) — refused rather than weaken security:")
|
|
317
|
+
for alg, reason in skipped:
|
|
318
|
+
print(f" • {alg:<26} {reason}")
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def demo_NTRU_ot():
|
|
322
|
+
print("=" * 72)
|
|
323
|
+
print("OT over NTRU_FO — NOT RUN")
|
|
324
|
+
print("=" * 72)
|
|
325
|
+
print(" Not wired in: NTRU_FO uses its own N=701 polynomial encoding, so it")
|
|
326
|
+
print(" needs a dedicated oblivious sampler (see oblivious_sampling.py).")
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
if __name__ == "__main__":
|
|
330
|
+
demo_oqs_ot()
|
|
331
|
+
print()
|
|
332
|
+
demo_NTRU_ot()
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: modularot
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Modular KEM-based 1-out-of-n Oblivious Transfer (semi-honest), agnostic to the underlying post-quantum KEM
|
|
5
|
+
Author: Gabriele Bottani
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/TheGaBr0/modularot
|
|
8
|
+
Project-URL: Source, https://github.com/TheGaBr0/modularot/tree/release
|
|
9
|
+
Project-URL: Issues, https://github.com/TheGaBr0/modularot/issues
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: cryptography>=41.0
|
|
14
|
+
Requires-Dist: liboqs-python
|
|
15
|
+
Provides-Extra: custom-kems
|
|
16
|
+
Requires-Dist: python-flint>=0.5; extra == "custom-kems"
|
|
17
|
+
Requires-Dist: GGH_crypto>=1.0.5; extra == "custom-kems"
|
|
18
|
+
Requires-Dist: numpy; extra == "custom-kems"
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
# modularot
|
|
22
|
+
Modular KEM-based 1-out-of-*n* Oblivious Transfer (semi-honest). The protocol never names a specific KEM: the only KEM-specific step, sampling an *oblivious* public key (a well-formed key nobody holds the secret for), is passed in as a callable.
|
|
23
|
+
|
|
24
|
+
The receiver sends one real public key for its choice and oblivious keys for the other branches. The sender encapsulates under every key and seals each message with ChaCha20-Poly1305. The receiver can only open the chosen one.
|
|
25
|
+
|
|
26
|
+
Samplers are included for ML-KEM / Kyber, FrodoKEM, NTRU-HPS / HRSS and sntrup761 (via liboqs), plus two research KEMs, `NTRU_FO` and `GGH_FO`, built with the Fujisaki-Okamoto transform.
|
|
27
|
+
|
|
28
|
+
## Install
|
|
29
|
+
```
|
|
30
|
+
pip install modularot
|
|
31
|
+
```
|
|
32
|
+
Requires the [liboqs](https://github.com/open-quantum-safe/liboqs) C library, installed before `liboqs-python`. The custom KEMs need an extra (`python-flint`):
|
|
33
|
+
```
|
|
34
|
+
pip install "modularot[custom-kems]"
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Usage
|
|
38
|
+
```python
|
|
39
|
+
from modularot import run_ot, oqs_kem_factory, resolve_oqs
|
|
40
|
+
|
|
41
|
+
result = run_ot(
|
|
42
|
+
make_kem=oqs_kem_factory("ML-KEM-768"),
|
|
43
|
+
sampler=resolve_oqs("ML-KEM-768"),
|
|
44
|
+
label="ML-KEM-768",
|
|
45
|
+
choice=1, # branch the receiver wants
|
|
46
|
+
n=4, # 1-out-of-4
|
|
47
|
+
)
|
|
48
|
+
assert result["ok"] # receiver got the message it asked for
|
|
49
|
+
assert result["secure"] # receiver could not open any other branch
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Command line:
|
|
53
|
+
```
|
|
54
|
+
modularot run --kem ML-KEM-768 --n 3 --choice 1
|
|
55
|
+
modularot list-kems
|
|
56
|
+
modularot bench --ns 2 4 8 --csv out.csv
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Other KEMs
|
|
60
|
+
Wrap the KEM in a `KEMAdapter(gen, encap, decap)` (all on `bytes`; `encap` returns `(shared_secret, ciphertext)`) and write a sampler `real_pk -> oblivious_pk` that returns a key in the same encoding as a real one, without running key generation. Then pass both to `run_ot`.
|
|
61
|
+
|
|
62
|
+
## Limits
|
|
63
|
+
Semi-honest security only. `NTRU_FO` and `GGH_FO` are research code, not quantum-safe or production-ready.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
modularot/__init__.py,sha256=hlwEezZpoqNKbGYYky8hAdoyxMj5IN6bpJ6-YJow7FE,1339
|
|
2
|
+
modularot/cli.py,sha256=YGL6GlkP9oyNlBlOtsQMB94DIqR6eBnFnelwzocAvmA,16463
|
|
3
|
+
modularot/oblivious_sampling.py,sha256=g6XU3lOcJGCScMhVut3qA0Y2ef6igXVOYv-FW4zkdOg,8218
|
|
4
|
+
modularot/ot_protocol.py,sha256=0iTDW5ZWjbS5XGfjYbLXgPq1d--x_TDfvogzz6gnQx8,13490
|
|
5
|
+
modularot/custom_kems/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
modularot/custom_kems/ggh_fo/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
modularot/custom_kems/ggh_fo/ggh_fo.py,sha256=DRbAcoPTRK6Es7Okgd44nZebW64_1Fu8TTzJsvO6YRM,10080
|
|
8
|
+
modularot/custom_kems/ntru_fo/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
modularot/custom_kems/ntru_fo/ntru_fo.py,sha256=EhcgWuEYWg10XMZwWdi-l7z9sCp_WmBW2dRx0oFB26s,11172
|
|
10
|
+
modularot/kem_adapter/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
11
|
+
modularot/kem_adapter/adapter.py,sha256=Wf1zgkk93DOUsmy61HbYwEQzx5DJgApOP4xb22QUeGE,1463
|
|
12
|
+
modularot-0.1.0.dist-info/licenses/LICENSE,sha256=vWJTxB9NcpQvWvMdTqMVReHPRGACxiPcF1mxWkSOtyU,1073
|
|
13
|
+
modularot-0.1.0.dist-info/METADATA,sha256=zx_v9YwIrErUpU_lfyMUl4y9E-zcICsgIU1qRcpa-kw,2653
|
|
14
|
+
modularot-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
15
|
+
modularot-0.1.0.dist-info/entry_points.txt,sha256=6qhJ1z0foIM1iFkwGgJeIoOMGSZYcLwGXSczS2Bp4z4,49
|
|
16
|
+
modularot-0.1.0.dist-info/top_level.txt,sha256=QAx_W3FvxDKhDzyJvgGY-_mPsW3JDXuBDY1dfFzC_kQ,10
|
|
17
|
+
modularot-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Gabriele Bottani
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
modularot
|