def ecdh_agree(privkey: datatypes.PrivateKey, pubkey: datatypes.PublicKey) -> bytes: """Performs a key exchange operation using the ECDH algorithm.""" privkey_as_int = int(cast(int, privkey)) ec_privkey = ec.derive_private_key(privkey_as_int, CURVE, default_backend()) pubkey_bytes = b'\x04' + pubkey.to_bytes() pubkey_nums = ec.EllipticCurvePublicNumbers.from_encoded_point(CURVE, pubkey_bytes) ec_pubkey = pubkey_nums.public_key(default_backend()) return ec_privkey.exchange(ec.ECDH(), ec_pubkey)
def ecdsa_verify(self, msg_hash: bytes, signature: BaseSignature, public_key: PublicKey) -> bool: der_encoded_signature = der.two_int_sequence_encoder( signature.r, signature.s) coincurve_public_key = self.keys.PublicKey(b"\x04" + public_key.to_bytes()) return coincurve_public_key.verify( der_encoded_signature, msg_hash, hasher=None, )
def ecdsa_verify(self, msg_hash: bytes, signature: BaseSignature, public_key: PublicKey) -> bool: # coincurve rejects signatures with a high s, so convert to the equivalent low s form low_s = coerce_low_s(signature.s) der_encoded_signature = der.two_int_sequence_encoder( signature.r, low_s) coincurve_public_key = self.keys.PublicKey(b"\x04" + public_key.to_bytes()) return coincurve_public_key.verify( der_encoded_signature, msg_hash, hasher=None, )
def ecdh_agree(privkey: datatypes.PrivateKey, pubkey: datatypes.PublicKey) -> bytes: """Performs a key exchange operation using the ECDH algorithm.""" privkey_as_int = int(cast(int, privkey)) ec_privkey = ec.derive_private_key(privkey_as_int, CURVE, default_backend()) pubkey_bytes = b'\x04' + pubkey.to_bytes() try: # either of these can raise a ValueError: pubkey_nums = ec.EllipticCurvePublicKey.from_encoded_point(CURVE, pubkey_bytes) ec_pubkey = pubkey_nums.public_numbers().public_key(default_backend()) except ValueError as exc: # Not all bytes can be made into valid public keys, see the warning at # https://cryptography.io/en/latest/hazmat/primitives/asymmetric/ec/ # under EllipticCurvePublicNumbers(x, y) raise _InvalidPublicKey(str(exc)) from exc return ec_privkey.exchange(ec.ECDH(), ec_pubkey)
def __init__(self, pubkey: datatypes.PublicKey, address: Address) -> None: self.pubkey = pubkey self.address = address self.id = big_endian_to_int(keccak(pubkey.to_bytes()))
def peer_id_from_pubkey(pubkey: datatypes.PublicKey) -> ID: algo = multihash.Func.sha2_256 mh_digest = multihash.digest(pubkey.to_bytes(), algo) return ID(mh_digest.encode())