py-libp2p/libp2p/crypto/key_exchange.py

29 lines
942 B
Python
Raw Normal View History

2019-08-24 05:43:36 +08:00
from typing import Callable, Tuple, cast
2019-08-23 22:54:59 +08:00
import Crypto.PublicKey.ECC as ECC
2019-08-24 05:43:36 +08:00
from libp2p.crypto.ecc import ECCPrivateKey, create_new_key_pair
2019-08-23 22:54:59 +08:00
from libp2p.crypto.keys import PublicKey
SharedKeyGenerator = Callable[[bytes], bytes]
def create_ephemeral_key_pair(curve_type: str) -> Tuple[PublicKey, SharedKeyGenerator]:
"""
Facilitates ECDH key exchange.
"""
if curve_type != "P-256":
raise NotImplementedError()
key_pair = create_new_key_pair(curve_type)
def _key_exchange(serialized_remote_public_key: bytes) -> bytes:
remote_public_key = ECC.import_key(serialized_remote_public_key)
curve_point = remote_public_key.pointQ
2019-08-24 05:43:36 +08:00
private_key = cast(ECCPrivateKey, key_pair.private_key)
secret_point = curve_point * private_key.impl.d
2019-08-23 22:54:59 +08:00
byte_size = secret_point.size_in_bytes()
2019-08-25 01:57:56 +08:00
return secret_point.x.to_bytes(byte_size)
2019-08-23 22:54:59 +08:00
return key_pair.public_key, _key_exchange