from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.kdf.hkdf import HKDF def generate_keypair(): private_key = ec.generate_private_key(ec.SECP256R1()) return private_key, private_key.public_key() def serialize_public_key(public_key: ec.EllipticCurvePublicKey) -> bytes: return public_key.public_bytes( encoding=serialization.Encoding.X962, format=serialization.PublicFormat.UncompressedPoint, ) def deserialize_public_key(data: bytes) -> ec.EllipticCurvePublicKey: return ec.EllipticCurvePublicKey.from_encoded_point( ec.SECP256R1(), data ) def derive_aes_key(private_key, peer_public_key) -> bytes: shared_secret = private_key.exchange(ec.ECDH(), peer_public_key) return HKDF( algorithm=hashes.SHA256(), length=32, salt=None, info=b'handshake', ).derive(shared_secret)