cryptoSL2024/ot.py

82 lines
2.0 KiB
Python
Raw Permalink Normal View History

2024-04-17 21:36:12 +02:00
import ecpy.curves as curves
import secrets
import pickle
import Crypto.Random
import Crypto.Cipher.AES
import Crypto.Protocol.KDF
import contextlib
2024-04-17 21:36:12 +02:00
curve = curves.Curve.get_curve("NIST-P224")
2024-04-17 22:39:25 +02:00
q = curve.size
2024-04-17 21:36:12 +02:00
g = curve.generator
2024-04-17 22:39:25 +02:00
def H(p: curves.Point, salt: bytes) -> bytes:
2024-04-17 21:36:12 +02:00
secret = pickle.dumps((p.x, p.y), protocol=4)
key = Crypto.Protocol.KDF.scrypt(secret, salt, 16, N=2**14, r=8, p=1)
return key[:32] # first 32 bytes of generated key
2024-04-17 21:36:12 +02:00
def E(key: bytes, message: bytes) -> tuple[bytes, bytes]:
cipher = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CTR)
ct = cipher.encrypt(message)
return (ct, cipher.nonce)
2024-04-17 21:36:12 +02:00
def D(key: bytes, encrypted_with_nonce: tuple[bytes, bytes]) -> bytes:
ct, nonce = encrypted_with_nonce
cipher = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CTR, nonce=nonce)
return cipher.decrypt(ct)
########################################################
# Workers
########################################################
def alice(m0: bytes, m1: bytes):
a = 1 + secrets.randbelow(q)
A = curve.mul_point(a, g)
B = yield A
salt = Crypto.Random.get_random_bytes(16)
k0 = H(curve.mul_point(a, B), salt)
k1 = H(curve.mul_point(a, curve.sub_point(B, A)), salt)
e0 = E(k0, m0)
e1 = E(k1, m1)
yield e0, e1, salt
def bob(c: bool):
b = 1 + secrets.randbelow(q)
A = yield
B = curve.mul_point(b, g)
if c:
B = curve.add_point(A, B)
e0, e1, salt = yield B
kc = H(curve.mul_point(b, A), salt)
2024-04-18 00:09:59 +02:00
yield D(kc, e1 if c else e0)
########################################################
# Arrows
########################################################
2024-04-17 21:36:12 +02:00
def main():
with contextlib.suppress(StopIteration):
a = alice(b"msg one", b"msg two")
b = bob(True)
A = a.send(None)
b.send(None)
B = b.send(A)
encrypted = a.send(B)
2024-04-18 00:09:59 +02:00
result = b.send(encrypted)
print(result)
2024-04-17 21:36:12 +02:00
if __name__ == "__main__":
main()