Python cryptography.hazmat.primitives.asymmetric.ec.ECDH Examples
The following are 30
code examples of cryptography.hazmat.primitives.asymmetric.ec.ECDH().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
cryptography.hazmat.primitives.asymmetric.ec
, or try the search function
.
Example #1
Source File: keyexchange_tls13.py From scapy with GNU General Public License v2.0 | 6 votes |
def post_build(self, pkt, pay): if not self.tls_session.frozen and self.server_share.privkey: # if there is a privkey, we assume the crypto library is ok privshare = self.tls_session.tls13_server_privshare if len(privshare) > 0: pkt_info = pkt.firstlayer().summary() log_runtime.info("TLS: overwriting previous server key share [%s]", pkt_info) # noqa: E501 group_name = _tls_named_groups[self.server_share.group] privshare[group_name] = self.server_share.privkey if group_name in self.tls_session.tls13_client_pubshares: privkey = self.server_share.privkey pubkey = self.tls_session.tls13_client_pubshares[group_name] if group_name in six.itervalues(_tls_named_ffdh_groups): pms = privkey.exchange(pubkey) elif group_name in six.itervalues(_tls_named_curves): if group_name in ["x25519", "x448"]: pms = privkey.exchange(pubkey) else: pms = privkey.exchange(ec.ECDH(), pubkey) self.tls_session.tls13_dhe_secret = pms return super(TLS_Ext_KeyShare_SH, self).post_build(pkt, pay)
Example #2
Source File: keyexchange.py From scapy with GNU General Public License v2.0 | 6 votes |
def fill_missing(self): s = self.tls_session params = s.client_kx_ecdh_params s.client_kx_privkey = ec.generate_private_key(params, default_backend()) pubkey = s.client_kx_privkey.public_key() x = pubkey.public_numbers().x y = pubkey.public_numbers().y self.ecdh_Yc = (b"\x04" + pkcs_i2osp(x, params.key_size // 8) + pkcs_i2osp(y, params.key_size // 8)) if s.client_kx_privkey and s.server_kx_pubkey: pms = s.client_kx_privkey.exchange(ec.ECDH(), s.server_kx_pubkey) s.pre_master_secret = pms s.compute_ms_and_derive_keys()
Example #3
Source File: keyexchange.py From scapy with GNU General Public License v2.0 | 6 votes |
def post_dissection(self, m): s = self.tls_session # if there are kx params and keys, we assume the crypto library is ok if s.client_kx_ecdh_params: try: # cryptography >= 2.5 import_point = ec.EllipticCurvePublicKey.from_encoded_point s.client_kx_pubkey = import_point(s.client_kx_ecdh_params, self.ecdh_Yc) except AttributeError: import_point = ec.EllipticCurvePublicNumbers.from_encoded_point pub_num = import_point(s.client_kx_ecdh_params, self.ecdh_Yc) s.client_kx_pubkey = pub_num.public_key(default_backend()) if s.server_kx_privkey and s.client_kx_pubkey: ZZ = s.server_kx_privkey.exchange(ec.ECDH(), s.client_kx_pubkey) s.pre_master_secret = ZZ s.compute_ms_and_derive_keys() # RSA Encryption (standard & export)
Example #4
Source File: fields.py From PGPy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def decrypt(self, pk, *args): km = pk.keymaterial if km.oid == EllipticCurveOID.Curve25519: v = x25519.X25519PublicKey.from_public_bytes(self.p.x) s = km.__privkey__().exchange(v) else: # assemble the public component of ephemeral key v v = ec.EllipticCurvePublicNumbers(self.p.x, self.p.y, km.oid.curve()).public_key(default_backend()) # compute s using the inverse of how it was derived during encryption s = km.__privkey__().exchange(ec.ECDH(), v) # derive the wrapping key z = km.kdf.derive_key(s, km.oid, PubKeyAlgorithm.ECDH, pk.fingerprint) # unwrap and unpad m _m = aes_key_unwrap(z, self.c, default_backend()) padder = PKCS7(64).unpadder() return padder.update(_m) + padder.finalize()
Example #5
Source File: enc_basic.py From XFLTReaT with MIT License | 6 votes |
def encryption_step_5(self, module, message, additional_data, cm): client_ephemeral_public = message[len(self.cmh_struct_encryption[4][0]):] c = module.lookup_client_pub(additional_data) try: public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(self.curve, "\x04"+client_ephemeral_public) except: common.internal_print("Erroneous key received from the client. Are you sure you are using the same settings on both sides?", -1) return module.cmh_struct[cm][4+module.is_caller_stateless()] client_ephemeral_public_key = public_numbers.public_key(default_backend()) server_ephemeral_private_key = c.get_encryption().get_private_key() c.get_encryption().set_shared_key(server_ephemeral_private_key.exchange(ec.ECDH(), client_ephemeral_public_key)) module.post_encryption_server(message[len(self.cmh_struct_encryption[4][0]):], additional_data) common.internal_print("Encryption key agreed with the client.", 1) return module.cmh_struct[cm][3] # checking for the key file values in the config
Example #6
Source File: encrypted_queries_tools.py From github-token with GNU General Public License v3.0 | 6 votes |
def encrypt(message, receiver_public_key): sender_private_key = ec.generate_private_key(ec.SECP256K1(), backend) shared_key = sender_private_key.exchange(ec.ECDH(), receiver_public_key) sender_public_key = sender_private_key.public_key() point = sender_public_key.public_numbers().encode_point() iv = '000000000000' xkdf = x963kdf.X963KDF( algorithm = hashes.SHA256(), length = 32, sharedinfo = '', backend = backend ) key = xkdf.derive(shared_key) encryptor = Cipher( algorithms.AES(key), modes.GCM(iv), backend = backend ).encryptor() ciphertext = encryptor.update(message) + encryptor.finalize() return point + encryptor.tag + ciphertext
Example #7
Source File: encrypted_queries_tools.py From github-token with GNU General Public License v3.0 | 6 votes |
def decrypt(message, receiver_private_key): point = message[0:65] tag = message[65:81] ciphertext = message[81:] sender_public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1(), point) sender_public_key = sender_public_numbers.public_key(backend) shared_key = receiver_private_key.exchange(ec.ECDH(), sender_public_key) iv = '000000000000' xkdf = x963kdf.X963KDF( algorithm = hashes.SHA256(), length = 32, sharedinfo = '', backend = backend ) key = xkdf.derive(shared_key) decryptor = Cipher( algorithms.AES(key), modes.GCM(iv,tag), backend = backend ).decryptor() message = decryptor.update(ciphertext) + decryptor.finalize() return message
Example #8
Source File: _kex.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def getSupportedKeyExchanges(): """ Get a list of supported key exchange algorithm names in order of preference. @return: A C{list} of supported key exchange algorithm names. @rtype: C{list} of L{bytes} """ from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import ec from twisted.conch.ssh.keys import _curveTable backend = default_backend() kexAlgorithms = _kexAlgorithms.copy() for keyAlgorithm in list(kexAlgorithms): if keyAlgorithm.startswith(b"ecdh"): keyAlgorithmDsa = keyAlgorithm.replace(b"ecdh", b"ecdsa") supported = backend.elliptic_curve_exchange_algorithm_supported( ec.ECDH(), _curveTable[keyAlgorithmDsa]) if not supported: kexAlgorithms.pop(keyAlgorithm) return sorted( kexAlgorithms, key = lambda kexAlgorithm: kexAlgorithms[kexAlgorithm].preference)
Example #9
Source File: jwa.py From jwcrypto with GNU Lesser General Public License v3.0 | 6 votes |
def wrap(self, key, bitsize, cek, headers): self._check_key(key) dk_size = self.keysize if self.keysize is None: if cek is not None: raise InvalidJWEOperation('ECDH-ES cannot use an existing CEK') alg = headers['enc'] dk_size = bitsize else: alg = headers['alg'] epk = JWK.generate(kty=key.key_type, crv=key.key_curve) dk = self._derive(epk.get_op_key('unwrapKey'), key.get_op_key('wrapKey'), alg, dk_size, headers) if self.keysize is None: ret = {'cek': dk} else: aeskw = self.aeskwmap[self.keysize]() kek = JWK(kty="oct", use="enc", k=base64url_encode(dk)) ret = aeskw.wrap(kek, bitsize, cek, headers) ret['header'] = {'epk': json_decode(epk.export_public())} return ret
Example #10
Source File: _kex.py From learn_python3_spider with MIT License | 6 votes |
def getSupportedKeyExchanges(): """ Get a list of supported key exchange algorithm names in order of preference. @return: A C{list} of supported key exchange algorithm names. @rtype: C{list} of L{bytes} """ from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import ec from twisted.conch.ssh.keys import _curveTable backend = default_backend() kexAlgorithms = _kexAlgorithms.copy() for keyAlgorithm in list(kexAlgorithms): if keyAlgorithm.startswith(b"ecdh"): keyAlgorithmDsa = keyAlgorithm.replace(b"ecdh", b"ecdsa") supported = backend.elliptic_curve_exchange_algorithm_supported( ec.ECDH(), _curveTable[keyAlgorithmDsa]) if not supported: kexAlgorithms.pop(keyAlgorithm) return sorted( kexAlgorithms, key = lambda kexAlgorithm: kexAlgorithms[kexAlgorithm].preference)
Example #11
Source File: fields.py From PGPy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def sign(self, sigdata, hash_alg): raise PGPError("Cannot sign with an ECDH key")
Example #12
Source File: keyexchange_tls13.py From scapy with GNU General Public License v2.0 | 5 votes |
def post_dissection(self, r): if not self.tls_session.frozen and self.server_share.pubkey: # if there is a pubkey, we assume the crypto library is ok pubshare = self.tls_session.tls13_server_pubshare if pubshare: pkt_info = r.firstlayer().summary() log_runtime.info("TLS: overwriting previous server key share [%s]", pkt_info) # noqa: E501 group_name = _tls_named_groups[self.server_share.group] pubshare[group_name] = self.server_share.pubkey if group_name in self.tls_session.tls13_client_privshares: pubkey = self.server_share.pubkey privkey = self.tls_session.tls13_client_privshares[group_name] if group_name in six.itervalues(_tls_named_ffdh_groups): pms = privkey.exchange(pubkey) elif group_name in six.itervalues(_tls_named_curves): if group_name in ["x25519", "x448"]: pms = privkey.exchange(pubkey) else: pms = privkey.exchange(ec.ECDH(), pubkey) self.tls_session.tls13_dhe_secret = pms elif group_name in self.tls_session.tls13_server_privshare: pubkey = self.tls_session.tls13_client_pubshares[group_name] privkey = self.tls_session.tls13_server_privshare[group_name] if group_name in six.itervalues(_tls_named_ffdh_groups): pms = privkey.exchange(pubkey) elif group_name in six.itervalues(_tls_named_curves): if group_name in ["x25519", "x448"]: pms = privkey.exchange(pubkey) else: pms = privkey.exchange(ec.ECDH(), pubkey) self.tls_session.tls13_dhe_secret = pms return super(TLS_Ext_KeyShare_SH, self).post_dissection(r)
Example #13
Source File: crypto.py From fabric-sdk-py with Apache License 2.0 | 5 votes |
def encrypt(self, public_key, plain_text): """ECIES encrypt plain text. First create a ephemeral ecdsa key pair, then serialize the public key for part of result. Then derived a shared key based ecdh, using the key based hkdf to generate aes key and hmac key, using aes-256-cfb to generate the part of result. Last using hmac-sha3 and the part of previous step to generate last part of result. :param public_key: public key :param plain_text: plain text :return: cipher text """ ephemeral_private_key = self.generate_private_key() rb = ephemeral_private_key.public_key().public_bytes( serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint ) z = ephemeral_private_key.exchange(ec.ECDH(), public_key) hkdf_output = Hkdf(salt=None, input_key_material=z, hash=self._hash) \ .expand(length=AES_KEY_LENGTH + HMAC_KEY_LENGTH) aes_key = hkdf_output[:AES_KEY_LENGTH] hmac_key = hkdf_output[AES_KEY_LENGTH:AES_KEY_LENGTH + HMAC_KEY_LENGTH] aes_cipher = AES.new(aes_key, AES.MODE_CFB) em = aes_cipher.iv + aes_cipher.encrypt(plain_text) mac = hmac.new(hmac_key, em, self._hash) d = mac.digest() return rb + em + d
Example #14
Source File: backend.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def elliptic_curve_exchange_algorithm_supported(self, algorithm, curve): return ( self.elliptic_curve_supported(curve) and isinstance(algorithm, ec.ECDH) )
Example #15
Source File: backend.py From quickstart-git2s3 with Apache License 2.0 | 5 votes |
def elliptic_curve_exchange_algorithm_supported(self, algorithm, curve): return ( self.elliptic_curve_supported(curve) and isinstance(algorithm, ec.ECDH) )
Example #16
Source File: ecies.py From trinity with MIT License | 5 votes |
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)
Example #17
Source File: ecc.py From synapse with Apache License 2.0 | 5 votes |
def exchange(self, pubkey): ''' Perform a ECDH key exchange with a public key. Args: pubkey (PubKey): A PubKey to perform the ECDH with. Returns: bytes: The ECDH bytes. This is deterministic for a given pubkey and private key. ''' try: return self.priv.exchange(c_ec.ECDH(), pubkey.publ) except ValueError as e: raise s_exc.BadEccExchange(mesg=str(e))
Example #18
Source File: backend.py From quickstart-redhat-openshift with Apache License 2.0 | 5 votes |
def elliptic_curve_exchange_algorithm_supported(self, algorithm, curve): return ( self.elliptic_curve_supported(curve) and isinstance(algorithm, ec.ECDH) )
Example #19
Source File: backend.py From teleport with Apache License 2.0 | 5 votes |
def elliptic_curve_exchange_algorithm_supported(self, algorithm, curve): return ( self.elliptic_curve_supported(curve) and isinstance(algorithm, ec.ECDH) )
Example #20
Source File: backend.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def elliptic_curve_exchange_algorithm_supported(self, algorithm, curve): return ( self.elliptic_curve_supported(curve) and self._lib.Cryptography_HAS_ECDH == 1 and isinstance(algorithm, ec.ECDH) )
Example #21
Source File: backend.py From oss-ftp with MIT License | 5 votes |
def elliptic_curve_exchange_algorithm_supported(self, algorithm, curve): return ( self.elliptic_curve_supported(curve) and self._lib.Cryptography_HAS_ECDH == 1 and isinstance(algorithm, ec.ECDH) )
Example #22
Source File: ecies.py From pyquarkchain with MIT License | 5 votes |
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)
Example #23
Source File: jwa.py From jwcrypto with GNU Lesser General Public License v3.0 | 5 votes |
def _derive(self, privkey, pubkey, alg, bitsize, headers): # OtherInfo is defined in NIST SP 56A 5.8.1.2.1 # AlgorithmID otherinfo = struct.pack('>I', len(alg)) otherinfo += bytes(alg.encode('utf8')) # PartyUInfo apu = base64url_decode(headers['apu']) if 'apu' in headers else b'' otherinfo += struct.pack('>I', len(apu)) otherinfo += apu # PartyVInfo apv = base64url_decode(headers['apv']) if 'apv' in headers else b'' otherinfo += struct.pack('>I', len(apv)) otherinfo += apv # SuppPubInfo otherinfo += struct.pack('>I', bitsize) # no SuppPrivInfo # Shared Key generation if isinstance(privkey, ec.EllipticCurvePrivateKey): shared_key = privkey.exchange(ec.ECDH(), pubkey) else: # X25519/X448 shared_key = privkey.exchange(pubkey) ckdf = ConcatKDFHash(algorithm=hashes.SHA256(), length=_inbytes(bitsize), otherinfo=otherinfo, backend=self.backend) return ckdf.derive(shared_key)
Example #24
Source File: enc_basic.py From XFLTReaT with MIT License | 5 votes |
def encryption_step_4(self, module, message, additional_data, cm): server_ephemeral_public_key_stream = message[len(self.cmh_struct_encryption[3][0]):] try: public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(self.curve, "\x04"+server_ephemeral_public_key_stream) except: common.internal_print("Erroneous key received from the server. Are you sure you are using the same settings on both sides?", -1) return module.cmh_struct[cm][4+module.is_caller_stateless()] server_ephemeral_public_key = public_numbers.public_key(default_backend()) client_ephemeral_private_key = ec.generate_private_key(self.curve, default_backend()) client_ephemeral_public_key = client_ephemeral_private_key.public_key() module.encryption.set_private_key(client_ephemeral_private_key) module.encryption.set_public_key(client_ephemeral_public_key) pbk = client_ephemeral_public_key.public_numbers().encode_point()[1:] module.send(common.CONTROL_CHANNEL_BYTE, self.cmh_struct_encryption[4][0]+pbk, module.modify_additional_data(additional_data, 0)) module.encryption.set_shared_key(client_ephemeral_private_key.exchange(ec.ECDH(), server_ephemeral_public_key)) module.post_encryption_client(message[len(self.cmh_struct_encryption[3][0]):], additional_data) common.internal_print("Encryption key agreed with the server.", 1) return module.cmh_struct[cm][3] # server side. # Client's ephemeral public key received. Key exchanged and saved.
Example #25
Source File: enc_advanced.py From XFLTReaT with MIT License | 5 votes |
def encryption_step_5(self, module, message, additional_data, cm): client_ephemeral_public = message[len(self.cmh_struct_encryption[4][0]):] c = module.lookup_client_pub(additional_data) try: public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(self.curve, "\x04"+client_ephemeral_public) except: common.internal_print("Erroneous key received from the client. Are you sure you are using the same settings on both sides?", -1) return module.cmh_struct[cm][4+module.is_caller_stateless()] client_ephemeral_public_key = public_numbers.public_key(default_backend()) server_ephemeral_private_key = c.get_encryption().get_private_key() hkdf = HKDF(algorithm=hashes.SHA256(), length=32, salt="IRatherEatMaldonThanHimalayan", info=None, backend=default_backend()) c.get_encryption().set_shared_key(hkdf.derive(server_ephemeral_private_key.exchange(ec.ECDH(), client_ephemeral_public_key))) module.post_encryption_server(message[len(self.cmh_struct_encryption[4][0]):], additional_data) common.internal_print("Encryption key agreed with the client.", 1) return module.cmh_struct[cm][3] # checking for the key file values in the config
Example #26
Source File: enc_advanced.py From XFLTReaT with MIT License | 5 votes |
def encryption_step_4(self, module, message, additional_data, cm): server_ephemeral_public_key_stream = message[len(self.cmh_struct_encryption[3][0]):] try: public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(self.curve, "\x04"+server_ephemeral_public_key_stream) except: common.internal_print("Erroneous key received from the server. Are you sure you are using the same settings on both sides?", -1) return module.cmh_struct[cm][4+module.is_caller_stateless()] server_ephemeral_public_key = public_numbers.public_key(default_backend()) client_ephemeral_private_key = ec.generate_private_key(self.curve, default_backend()) client_ephemeral_public_key = client_ephemeral_private_key.public_key() module.encryption.set_private_key(client_ephemeral_private_key) module.encryption.set_public_key(client_ephemeral_public_key) pbk = client_ephemeral_public_key.public_numbers().encode_point()[1:] module.send(common.CONTROL_CHANNEL_BYTE, self.cmh_struct_encryption[4][0]+pbk, module.modify_additional_data(additional_data, 0)) hkdf = HKDF(algorithm=hashes.SHA256(), length=32, salt="IRatherEatMaldonThanHimalayan", info=None, backend=default_backend()) module.encryption.set_shared_key(hkdf.derive(client_ephemeral_private_key.exchange(ec.ECDH(), server_ephemeral_public_key))) module.post_encryption_client(message[len(self.cmh_struct_encryption[3][0]):], additional_data) common.internal_print("Encryption key agreed with the server.", 1) return module.cmh_struct[cm][3] # server side. # Client's ephemeral public key received. Key exchanged and saved.
Example #27
Source File: enc_advanced.py From XFLTReaT with MIT License | 5 votes |
def encryption_step_3(self, module, message, additional_data, cm): client_public_key_stream = message[len(self.cmh_struct_encryption[2][0]):] try: public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(self.curve, "\x04"+client_public_key_stream) except: common.internal_print("Erroneous key received from the client. Are you sure you are using the same settings on both sides?", -1) return module.cmh_struct[cm][4+module.is_caller_stateless()] client_public_key = public_numbers.public_key(default_backend()) c = module.lookup_client_pub(additional_data) hkdf = HKDF(algorithm=hashes.SHA256(), length=32, salt="IRatherEatMaldonThanHimalayan", info=None, backend=default_backend()) c.get_encryption().set_shared_key(hkdf.derive(self.server_private_key.exchange(ec.ECDH(), client_public_key))) server_ephemeral_private_key = ec.generate_private_key(self.curve, default_backend()) server_ephemeral_public_key = server_ephemeral_private_key.public_key() # no need to save, but who knows?! c.get_encryption().set_private_key(server_ephemeral_private_key) c.get_encryption().set_public_key(server_ephemeral_public_key) c.get_encryption().set_encrypted(True) pbk = server_ephemeral_public_key.public_numbers().encode_point()[1:] module.send(common.CONTROL_CHANNEL_BYTE, self.cmh_struct_encryption[3][0]+pbk, module.modify_additional_data(additional_data, 1)) return module.cmh_struct[cm][3] # client side. # Server's ephemeral receveid, client generates an ephemeral keypair as # well. Client sends its ephemeral's public key to the server. # Since this is the last client side function called, we invoke the # next step that is most probably the authentication, defined in the # post_encryption_client() function.
Example #28
Source File: transport.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 4 votes |
def ssh_KEXINIT(self, packet): """ Called when we receive a MSG_KEXINIT message. For a description of the packet, see SSHTransportBase.ssh_KEXINIT(). Additionally, this method sends the first key exchange packet. If the agreed-upon exchange is ECDH, generate a key pair for the corresponding curve and send the public key. If the agreed-upon exchange has a fixed prime/generator group, generate a public key and send it in a MSG_KEXDH_INIT message. Otherwise, ask for a 2048 bit group with a MSG_KEX_DH_GEX_REQUEST message. """ if SSHTransportBase.ssh_KEXINIT(self, packet) is None: # Connection was disconnected while doing base processing. # Maybe no common protocols were agreed. return # Are we using ECDH? if _kex.isEllipticCurve(self.kexAlg): # Find the base curve info self.curve = keys._curveTable[b'ecdsa' + self.kexAlg[4:]] # Generate the keys self.ecPriv = ec.generate_private_key(self.curve, default_backend()) self.ecPub = self.ecPriv.public_key() # DH_GEX_REQUEST_OLD is the same number we need. self.sendPacket( MSG_KEX_DH_GEX_REQUEST_OLD, NS(self.ecPub.public_numbers().encode_point())) elif _kex.isFixedGroup(self.kexAlg): # We agreed on a fixed group key exchange algorithm. self.x = _generateX(randbytes.secureRandom, 512) self.g, self.p = _kex.getDHGeneratorAndPrime(self.kexAlg) self.e = _MPpow(self.g, self.x, self.p) self.sendPacket(MSG_KEXDH_INIT, self.e) else: # We agreed on a dynamic group. Tell the server what range of # group sizes we accept, and what size we prefer; the server # will then select a group. self.sendPacket( MSG_KEX_DH_GEX_REQUEST, struct.pack( '!LLL', self._dhMinimalGroupSize, self._dhPreferredGroupSize, self._dhMaximalGroupSize, ))
Example #29
Source File: transport.py From learn_python3_spider with MIT License | 4 votes |
def ssh_KEXINIT(self, packet): """ Called when we receive a MSG_KEXINIT message. For a description of the packet, see SSHTransportBase.ssh_KEXINIT(). Additionally, this method sends the first key exchange packet. If the agreed-upon exchange is ECDH, generate a key pair for the corresponding curve and send the public key. If the agreed-upon exchange has a fixed prime/generator group, generate a public key and send it in a MSG_KEXDH_INIT message. Otherwise, ask for a 2048 bit group with a MSG_KEX_DH_GEX_REQUEST message. """ if SSHTransportBase.ssh_KEXINIT(self, packet) is None: # Connection was disconnected while doing base processing. # Maybe no common protocols were agreed. return # Are we using ECDH? if _kex.isEllipticCurve(self.kexAlg): # Find the base curve info self.curve = keys._curveTable[b'ecdsa' + self.kexAlg[4:]] # Generate the keys self.ecPriv = ec.generate_private_key(self.curve, default_backend()) self.ecPub = self.ecPriv.public_key() # DH_GEX_REQUEST_OLD is the same number we need. self.sendPacket( MSG_KEX_DH_GEX_REQUEST_OLD, NS(self.ecPub.public_bytes( serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint )) ) elif _kex.isFixedGroup(self.kexAlg): # We agreed on a fixed group key exchange algorithm. self.g, self.p = _kex.getDHGeneratorAndPrime(self.kexAlg) self._startEphemeralDH() self.sendPacket(MSG_KEXDH_INIT, self.dhSecretKeyPublicMP) else: # We agreed on a dynamic group. Tell the server what range of # group sizes we accept, and what size we prefer; the server # will then select a group. self.sendPacket( MSG_KEX_DH_GEX_REQUEST, struct.pack( '!LLL', self._dhMinimalGroupSize, self._dhPreferredGroupSize, self._dhMaximalGroupSize, ))
Example #30
Source File: crypto.py From fabric-sdk-py with Apache License 2.0 | 4 votes |
def decrypt(self, private_key, cipher_text): """ECIES decrypt cipher text. First restore the ephemeral public key from bytes(97 bytes for 384, 65 bytes for 256). Then derived a shared key based ecdh, using the key based hkdf to generate aes key and hmac key, using hmac-sha3 to verify the hmac bytes. Last using aes-256-cfb to decrypt the bytes. :param private_key: private key :param cipher_text: cipher text :return: plain text """ key_len = private_key.curve.key_size if key_len != self.curve.key_size: raise ValueError( "Invalid key. Input security level {} does not " "match the current security level {}".format( key_len, self.curve.key_size)) d_len = key_len >> 3 rb_len = ((key_len + 7) // 8) * 2 + 1 ct_len = len(cipher_text) if ct_len <= rb_len + d_len: raise ValueError( "Illegal cipherText length: cipher text length {} " "must be > rb length plus d_len {}".format(ct_len, rb_len + d_len) ) rb = cipher_text[:rb_len] em = cipher_text[rb_len:ct_len - d_len] d = cipher_text[ct_len - d_len:ct_len] ephemeral_public_key = EllipticCurvePublicKey \ .from_encoded_point(self.curve(), rb) z = private_key.exchange(ec.ECDH(), ephemeral_public_key) hkdf_output = Hkdf(salt=None, input_key_material=z, hash=self._hash) \ .expand(length=AES_KEY_LENGTH + HMAC_KEY_LENGTH) aes_key = hkdf_output[:AES_KEY_LENGTH] hmac_key = hkdf_output[AES_KEY_LENGTH:AES_KEY_LENGTH + HMAC_KEY_LENGTH] mac = hmac.new(hmac_key, em, self._hash) recovered_d = mac.digest() if not constant_time.bytes_eq(recovered_d, d): raise ValueError("Hmac verify failed.") iv = em[:IV_LENGTH] aes_cipher = AES.new(key=aes_key, mode=AES.MODE_CFB, iv=iv) return aes_cipher.decrypt(em[IV_LENGTH:len(em)])