Python cryptography.hazmat.primitives.asymmetric.ec.SECP256R1 Examples
The following are 30
code examples of cryptography.hazmat.primitives.asymmetric.ec.SECP256R1().
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: serialization.py From quickstart-git2s3 with Apache License 2.0 | 6 votes |
def _load_ssh_ecdsa_public_key(expected_key_type, decoded_data, backend): curve_name, rest = _ssh_read_next_string(decoded_data) data, rest = _ssh_read_next_string(rest) if expected_key_type != b"ecdsa-sha2-" + curve_name: raise ValueError( 'Key header and key body contain different key type values.' ) if rest: raise ValueError('Key body contains extra bytes.') curve = { b"nistp256": ec.SECP256R1, b"nistp384": ec.SECP384R1, b"nistp521": ec.SECP521R1, }[curve_name]() if six.indexbytes(data, 0) != 4: raise NotImplementedError( "Compressed elliptic curve points are not supported" ) numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(curve, data) return numbers.public_key(backend)
Example #2
Source File: ssh.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _load_ssh_ecdsa_public_key(expected_key_type, decoded_data, backend): curve_name, rest = _ssh_read_next_string(decoded_data) data, rest = _ssh_read_next_string(rest) if expected_key_type != b"ecdsa-sha2-" + curve_name: raise ValueError( 'Key header and key body contain different key type values.' ) if rest: raise ValueError('Key body contains extra bytes.') curve = { b"nistp256": ec.SECP256R1, b"nistp384": ec.SECP384R1, b"nistp521": ec.SECP521R1, }[curve_name]() if six.indexbytes(data, 0) != 4: raise NotImplementedError( "Compressed elliptic curve points are not supported" ) return ec.EllipticCurvePublicKey.from_encoded_point(curve, data)
Example #3
Source File: signature_handler.py From ontology-python-sdk with GNU Lesser General Public License v3.0 | 6 votes |
def generate_signature(self, pri_key: str, msg: bytes) -> str: if self.__scheme == SignatureScheme.SHA224withECDSA: private_key = ec.derive_private_key(int(pri_key, 16), ec.SECP224R1(), default_backend()) signature = private_key.sign( msg, ec.ECDSA(hashes.SHA224()) ) elif self.__scheme == SignatureScheme.SHA256withECDSA: private_key = ec.derive_private_key(int(pri_key, 16), ec.SECP256R1(), default_backend()) signature = private_key.sign( msg, ec.ECDSA(hashes.SHA256()) ) elif self.__scheme == SignatureScheme.SHA384withECDSA: private_key = ec.derive_private_key(int(pri_key, 16), ec.SECP384R1(), default_backend()) signature = private_key.sign( msg, ec.ECDSA(hashes.SHA384()) ) else: raise SDKException(ErrorCode.other_error('Invalid signature scheme.')) sign = SignatureHandler.dsa_der_to_plain(signature) return sign
Example #4
Source File: ecdsakey.py From imoocc with GNU General Public License v2.0 | 6 votes |
def generate(cls, curve=ec.SECP256R1(), progress_func=None, bits=None): """ Generate a new private ECDSA key. This factory function can be used to generate a new host key or authentication key. :param function progress_func: Not used for this type of key. :returns: A new private key (`.ECDSAKey`) object """ if bits is not None: curve = cls._ECDSA_CURVES.get_by_key_length(bits) if curve is None: raise ValueError("Unsupported key length: %d"%(bits)) curve = curve.curve_class() private_key = ec.generate_private_key(curve, backend=default_backend()) return ECDSAKey(vals=(private_key, private_key.public_key())) ### internals...
Example #5
Source File: test_keys.py From learn_python3_spider with MIT License | 6 votes |
def test_fromPrivateBlobECDSA(self): """ A private EC key is correctly generated from a private key blob. """ from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives import serialization publicNumbers = ec.EllipticCurvePublicNumbers( x=keydata.ECDatanistp256['x'], y=keydata.ECDatanistp256['y'], curve=ec.SECP256R1()) ecblob = ( common.NS(keydata.ECDatanistp256['curve']) + common.NS(keydata.ECDatanistp256['curve'][-8:]) + common.NS(publicNumbers.public_key(default_backend()).public_bytes( serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint )) + common.MP(keydata.ECDatanistp256['privateValue']) ) eckey = keys.Key._fromString_PRIVATE_BLOB(ecblob) self.assertFalse(eckey.isPublic()) self.assertEqual(keydata.ECDatanistp256, eckey.data())
Example #6
Source File: cryptography_backend.py From python-jose with MIT License | 6 votes |
def _process_jwk(self, jwk_dict): if not jwk_dict.get('kty') == 'EC': raise JWKError("Incorrect key type. Expected: 'EC', Received: %s" % jwk_dict.get('kty')) if not all(k in jwk_dict for k in ['x', 'y', 'crv']): raise JWKError('Mandatory parameters are missing') x = base64_to_long(jwk_dict.get('x')) y = base64_to_long(jwk_dict.get('y')) curve = { 'P-256': ec.SECP256R1, 'P-384': ec.SECP384R1, 'P-521': ec.SECP521R1, }[jwk_dict['crv']] public = ec.EllipticCurvePublicNumbers(x, y, curve()) if 'd' in jwk_dict: d = base64_to_long(jwk_dict.get('d')) private = ec.EllipticCurvePrivateNumbers(d, public) return private.private_key(self.cryptography_backend()) else: return public.public_key(self.cryptography_backend())
Example #7
Source File: ssh.py From learn_python3_spider with MIT License | 6 votes |
def _load_ssh_ecdsa_public_key(expected_key_type, decoded_data, backend): curve_name, rest = _ssh_read_next_string(decoded_data) data, rest = _ssh_read_next_string(rest) if expected_key_type != b"ecdsa-sha2-" + curve_name: raise ValueError( 'Key header and key body contain different key type values.' ) if rest: raise ValueError('Key body contains extra bytes.') curve = { b"nistp256": ec.SECP256R1, b"nistp384": ec.SECP384R1, b"nistp521": ec.SECP521R1, }[curve_name]() if six.indexbytes(data, 0) != 4: raise NotImplementedError( "Compressed elliptic curve points are not supported" ) return ec.EllipticCurvePublicKey.from_encoded_point(curve, data)
Example #8
Source File: serialization.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def _load_ssh_ecdsa_public_key(expected_key_type, decoded_data, backend): curve_name, rest = _ssh_read_next_string(decoded_data) data, rest = _ssh_read_next_string(rest) if expected_key_type != b"ecdsa-sha2-" + curve_name: raise ValueError( 'Key header and key body contain different key type values.' ) if rest: raise ValueError('Key body contains extra bytes.') curve = { b"nistp256": ec.SECP256R1, b"nistp384": ec.SECP384R1, b"nistp521": ec.SECP521R1, }[curve_name]() if six.indexbytes(data, 0) != 4: raise NotImplementedError( "Compressed elliptic curve points are not supported" ) numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(curve, data) return numbers.public_key(backend)
Example #9
Source File: serialization.py From teleport with Apache License 2.0 | 6 votes |
def _load_ssh_ecdsa_public_key(expected_key_type, decoded_data, backend): curve_name, rest = _ssh_read_next_string(decoded_data) data, rest = _ssh_read_next_string(rest) if expected_key_type != b"ecdsa-sha2-" + curve_name: raise ValueError( 'Key header and key body contain different key type values.' ) if rest: raise ValueError('Key body contains extra bytes.') curve = { b"nistp256": ec.SECP256R1, b"nistp384": ec.SECP384R1, b"nistp521": ec.SECP521R1, }[curve_name]() if six.indexbytes(data, 0) != 4: raise NotImplementedError( "Compressed elliptic curve points are not supported" ) numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(curve, data) return numbers.public_key(backend)
Example #10
Source File: ssh.py From teleport with Apache License 2.0 | 6 votes |
def _load_ssh_ecdsa_public_key(expected_key_type, decoded_data, backend): curve_name, rest = _ssh_read_next_string(decoded_data) data, rest = _ssh_read_next_string(rest) if expected_key_type != b"ecdsa-sha2-" + curve_name: raise ValueError( 'Key header and key body contain different key type values.' ) if rest: raise ValueError('Key body contains extra bytes.') curve = { b"nistp256": ec.SECP256R1, b"nistp384": ec.SECP384R1, b"nistp521": ec.SECP521R1, }[curve_name]() if six.indexbytes(data, 0) != 4: raise NotImplementedError( "Compressed elliptic curve points are not supported" ) return ec.EllipticCurvePublicKey.from_encoded_point(curve, data)
Example #11
Source File: ssh.py From teleport with Apache License 2.0 | 6 votes |
def _load_ssh_ecdsa_public_key(expected_key_type, decoded_data, backend): curve_name, rest = _ssh_read_next_string(decoded_data) data, rest = _ssh_read_next_string(rest) if expected_key_type != b"ecdsa-sha2-" + curve_name: raise ValueError( 'Key header and key body contain different key type values.' ) if rest: raise ValueError('Key body contains extra bytes.') curve = { b"nistp256": ec.SECP256R1, b"nistp384": ec.SECP384R1, b"nistp521": ec.SECP521R1, }[curve_name]() if six.indexbytes(data, 0) != 4: raise NotImplementedError( "Compressed elliptic curve points are not supported" ) return ec.EllipticCurvePublicKey.from_encoded_point(curve, data)
Example #12
Source File: ssh.py From quickstart-redhat-openshift with Apache License 2.0 | 6 votes |
def _load_ssh_ecdsa_public_key(expected_key_type, decoded_data, backend): curve_name, rest = _ssh_read_next_string(decoded_data) data, rest = _ssh_read_next_string(rest) if expected_key_type != b"ecdsa-sha2-" + curve_name: raise ValueError( 'Key header and key body contain different key type values.' ) if rest: raise ValueError('Key body contains extra bytes.') curve = { b"nistp256": ec.SECP256R1, b"nistp384": ec.SECP384R1, b"nistp521": ec.SECP521R1, }[curve_name]() if six.indexbytes(data, 0) != 4: raise NotImplementedError( "Compressed elliptic curve points are not supported" ) return ec.EllipticCurvePublicKey.from_encoded_point(curve, data)
Example #13
Source File: crypto.py From fabric-sdk-py with Apache License 2.0 | 5 votes |
def __init__(self, security_level=CURVE_P_256_Size, hash_algorithm=SHA2): """ Init curve and hash function. :param security_level: security level :param hash_algorithm: hash function :return: an instance of Ecies """ if security_level == CURVE_P_256_Size: # order = openssl.backend._lib.BN_new() # curve = openssl.backend._lib.EC_GROUP_new_by_curve_name( # openssl.backend._lib.NID_X9_62_prime256v1) # openssl.backend._lib.EC_GROUP_get_order( # curve, order, openssl.backend._ffi.NULL) self.order = int("115792089210356248762697446949407573529" "996955224135760342422259061068512044369") self.half_order = self.order >> 1 self.curve = ec.SECP256R1 self.sign_hash_algorithm = hashes.SHA256() else: # order = openssl.backend._lib.BN_new() # curve = openssl.backend._lib.EC_GROUP_new_by_curve_name( # openssl.backend._lib.NID_secp384r1) # openssl.backend._lib.EC_GROUP_get_order( # curve, order, openssl.backend._ffi.NULL) self.order = int("39402006196394479212279040100" "14361380507973927046544666794" "69052796276593991132635693989" "56308152294913554433653942643") self.half_order = self.order >> 1 self.curve = ec.SECP384R1 self.sign_hash_algorithm = hashes.SHA384() if hash_algorithm == SHA2: self._hash = hashlib.sha256 elif hash_algorithm == SHA3 and security_level == CURVE_P_256_Size: self._hash = hashlib.sha3_256 else: self._hash = hashlib.sha3_384
Example #14
Source File: backend.py From quickstart-git2s3 with Apache License 2.0 | 5 votes |
def _openssh_public_key_bytes(self, key): if isinstance(key, rsa.RSAPublicKey): public_numbers = key.public_numbers() return b"ssh-rsa " + base64.b64encode( serialization._ssh_write_string(b"ssh-rsa") + serialization._ssh_write_mpint(public_numbers.e) + serialization._ssh_write_mpint(public_numbers.n) ) elif isinstance(key, dsa.DSAPublicKey): public_numbers = key.public_numbers() parameter_numbers = public_numbers.parameter_numbers return b"ssh-dss " + base64.b64encode( serialization._ssh_write_string(b"ssh-dss") + serialization._ssh_write_mpint(parameter_numbers.p) + serialization._ssh_write_mpint(parameter_numbers.q) + serialization._ssh_write_mpint(parameter_numbers.g) + serialization._ssh_write_mpint(public_numbers.y) ) else: assert isinstance(key, ec.EllipticCurvePublicKey) public_numbers = key.public_numbers() try: curve_name = { ec.SECP256R1: b"nistp256", ec.SECP384R1: b"nistp384", ec.SECP521R1: b"nistp521", }[type(public_numbers.curve)] except KeyError: raise ValueError( "Only SECP256R1, SECP384R1, and SECP521R1 curves are " "supported by the SSH public key format" ) return b"ecdsa-sha2-" + curve_name + b" " + base64.b64encode( serialization._ssh_write_string(b"ecdsa-sha2-" + curve_name) + serialization._ssh_write_string(curve_name) + serialization._ssh_write_string(public_numbers.encode_point()) )
Example #15
Source File: Mastodon.py From Mastodon.py with MIT License | 5 votes |
def push_subscription_generate_keys(self): """ Generates a private key, public key and shared secret for use in webpush subscriptions. Returns two dicts: One with the private key and shared secret and another with the public key and shared secret. """ if not IMPL_HAS_CRYPTO: raise NotImplementedError('To use the crypto tools, please install the webpush feature dependencies.') push_key_pair = ec.generate_private_key(ec.SECP256R1(), default_backend()) push_key_priv = push_key_pair.private_numbers().private_value crypto_ver = cryptography.__version__ if len(crypto_ver) < 5: crypto_ver += ".0" if bigger_version(crypto_ver, "2.5.0") == crypto_ver: push_key_pub = push_key_pair.public_key().public_bytes(serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint) else: push_key_pub = push_key_pair.public_key().public_numbers().encode_point() push_shared_secret = os.urandom(16) priv_dict = { 'privkey': push_key_priv, 'auth': push_shared_secret } pub_dict = { 'pubkey': push_key_pub, 'auth': push_shared_secret } return priv_dict, pub_dict
Example #16
Source File: Mastodon.py From Mastodon.py with MIT License | 5 votes |
def push_subscription_decrypt_push(self, data, decrypt_params, encryption_header, crypto_key_header): """ Decrypts `data` received in a webpush request. Requires the private key dict from `push_subscription_generate_keys()`_ (`decrypt_params`) as well as the Encryption and server Crypto-Key headers from the received webpush Returns the decoded webpush as a `push notification dict`_. """ if (not IMPL_HAS_ECE) or (not IMPL_HAS_CRYPTO): raise NotImplementedError('To use the crypto tools, please install the webpush feature dependencies.') salt = self.__decode_webpush_b64(encryption_header.split("salt=")[1].strip()) dhparams = self.__decode_webpush_b64(crypto_key_header.split("dh=")[1].split(";")[0].strip()) p256ecdsa = self.__decode_webpush_b64(crypto_key_header.split("p256ecdsa=")[1].strip()) dec_key = ec.derive_private_key(decrypt_params['privkey'], ec.SECP256R1(), default_backend()) decrypted = http_ece.decrypt( data, salt = salt, key = p256ecdsa, private_key = dec_key, dh = dhparams, auth_secret=decrypt_params['auth'], keylabel = "P-256", version = "aesgcm" ) return json.loads(decrypted.decode('utf-8'), object_hook = Mastodon.__json_hooks) ### # Blurhash utilities ###
Example #17
Source File: cert.py From scapy with GNU General Public License v2.0 | 5 votes |
def fill_and_store(self, curve=None): curve = curve or ec.SECP256R1 self.key = ec.generate_private_key(curve(), default_backend()) self.pubkey = self.key.public_key()
Example #18
Source File: utils.py From django-ca with GNU General Public License v3.0 | 5 votes |
def validate_key_parameters(key_size=None, key_type='RSA', ecc_curve=None): """Validate parameters for private key generation and return sanitized values. This function can be used to fail early if invalid parameters are passed, before the private key is generated. >>> validate_key_parameters() # defaults (1024, 'RSA', None) >>> validate_key_parameters(4096, 'ECC', None) # doctest: +ELLIPSIS (None, 'ECC', <cryptography.hazmat.primitives.asymmetric.ec.SECP256R1 object at ...>) >>> validate_key_parameters(4000, 'RSA', None) Traceback (most recent call last): ... ValueError: 4000: Key size must be a power of two """ if key_type is None: key_type = 'RSA' if key_type == 'ECC': key_size = None ecc_curve = parse_key_curve(ecc_curve) elif key_type in ['DSA', 'RSA']: if key_size is None: key_size = ca_settings.CA_DEFAULT_KEY_SIZE if not is_power2(key_size): raise ValueError("%s: Key size must be a power of two" % key_size) elif key_size < ca_settings.CA_MIN_KEY_SIZE: raise ValueError("%s: Key size must be least %s bits" % ( key_size, ca_settings.CA_MIN_KEY_SIZE)) else: raise ValueError('%s: Unknown key type' % key_type) return key_size, key_type, ecc_curve
Example #19
Source File: test_create_key.py From sros2 with Apache License 2.0 | 5 votes |
def test_key_pem(enclave_keys_dir): private_key = load_private_key(enclave_keys_dir / 'key.pem') assert isinstance(private_key, ec.EllipticCurvePrivateKey) assert private_key.key_size == 256 public_key = private_key.public_key() assert isinstance(public_key.curve, ec.SECP256R1) assert public_key.key_size == 256
Example #20
Source File: test_EC.py From python-jose with MIT License | 5 votes |
def test_cryptography_sig_component_length(algorithm, expected_length): # Put mapping inside here to avoid more complex handling for test runs that do not have pyca/cryptography mapping = { ALGORITHMS.ES256: CryptographyEc.SECP256R1, ALGORITHMS.ES384: CryptographyEc.SECP384R1, ALGORITHMS.ES512: CryptographyEc.SECP521R1, } key = CryptographyECKey( CryptographyEc.generate_private_key(mapping[algorithm](), backend=CryptographyBackend()), algorithm ) assert key._sig_component_length() == expected_length
Example #21
Source File: __init__.py From agent with MIT License | 5 votes |
def generate_cert(device_id): private_key = ec.generate_private_key( ec.SECP256R1(), default_backend() ) builder = x509.CertificateSigningRequestBuilder() builder = builder.subject_name(x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, u'{}'.format(device_id)), x509.NameAttribute(NameOID.COUNTRY_NAME, u'UK'), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'London'), x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'Web of Trusted Things, Ltd'), ])) builder = builder.add_extension( x509.SubjectAlternativeName( [x509.DNSName(u'{}'.format(device_id))] ), critical=False ) csr = builder.sign(private_key, hashes.SHA256(), default_backend()) serialized_private_key = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption(), ) serialized_csr = csr.public_bytes(serialization.Encoding.PEM) return { 'csr': serialized_csr.decode(), 'key': serialized_private_key.decode() }
Example #22
Source File: jwk.py From jwcrypto with GNU Lesser General Public License v3.0 | 5 votes |
def _get_curve_by_name(self, name): if name == 'P-256': return ec.SECP256R1() elif name == 'P-384': return ec.SECP384R1() elif name == 'P-521': return ec.SECP521R1() elif name == 'secp256k1': return ec.SECP256K1() elif name in _OKP_CURVES_TABLE: return name else: raise InvalidJWKValue('Unknown Elliptic Curve Type')
Example #23
Source File: utils.py From asap-authentication-python with MIT License | 5 votes |
def get_new_private_key_in_pem_format(self): private_key = ec.generate_private_key( ec.SECP256R1(), default_backend()) return private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption() )
Example #24
Source File: cert.py From scapy with GNU General Public License v2.0 | 5 votes |
def fill_and_store(self, curve=None): curve = curve or ec.SECP256R1 private_key = ec.generate_private_key(curve(), default_backend()) self.pubkey = private_key.public_key()
Example #25
Source File: backend.py From teleport with Apache License 2.0 | 5 votes |
def _openssh_public_key_bytes(self, key): if isinstance(key, rsa.RSAPublicKey): public_numbers = key.public_numbers() return b"ssh-rsa " + base64.b64encode( serialization._ssh_write_string(b"ssh-rsa") + serialization._ssh_write_mpint(public_numbers.e) + serialization._ssh_write_mpint(public_numbers.n) ) elif isinstance(key, dsa.DSAPublicKey): public_numbers = key.public_numbers() parameter_numbers = public_numbers.parameter_numbers return b"ssh-dss " + base64.b64encode( serialization._ssh_write_string(b"ssh-dss") + serialization._ssh_write_mpint(parameter_numbers.p) + serialization._ssh_write_mpint(parameter_numbers.q) + serialization._ssh_write_mpint(parameter_numbers.g) + serialization._ssh_write_mpint(public_numbers.y) ) else: assert isinstance(key, ec.EllipticCurvePublicKey) public_numbers = key.public_numbers() try: curve_name = { ec.SECP256R1: b"nistp256", ec.SECP384R1: b"nistp384", ec.SECP521R1: b"nistp521", }[type(public_numbers.curve)] except KeyError: raise ValueError( "Only SECP256R1, SECP384R1, and SECP521R1 curves are " "supported by the SSH public key format" ) return b"ecdsa-sha2-" + curve_name + b" " + base64.b64encode( serialization._ssh_write_string(b"ecdsa-sha2-" + curve_name) + serialization._ssh_write_string(curve_name) + serialization._ssh_write_string(public_numbers.encode_point()) )
Example #26
Source File: backend.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def _openssh_public_key_bytes(self, key): if isinstance(key, rsa.RSAPublicKey): public_numbers = key.public_numbers() return b"ssh-rsa " + base64.b64encode( serialization._ssh_write_string(b"ssh-rsa") + serialization._ssh_write_mpint(public_numbers.e) + serialization._ssh_write_mpint(public_numbers.n) ) elif isinstance(key, dsa.DSAPublicKey): public_numbers = key.public_numbers() parameter_numbers = public_numbers.parameter_numbers return b"ssh-dss " + base64.b64encode( serialization._ssh_write_string(b"ssh-dss") + serialization._ssh_write_mpint(parameter_numbers.p) + serialization._ssh_write_mpint(parameter_numbers.q) + serialization._ssh_write_mpint(parameter_numbers.g) + serialization._ssh_write_mpint(public_numbers.y) ) else: assert isinstance(key, ec.EllipticCurvePublicKey) public_numbers = key.public_numbers() try: curve_name = { ec.SECP256R1: b"nistp256", ec.SECP384R1: b"nistp384", ec.SECP521R1: b"nistp521", }[type(public_numbers.curve)] except KeyError: raise ValueError( "Only SECP256R1, SECP384R1, and SECP521R1 curves are " "supported by the SSH public key format" ) return b"ecdsa-sha2-" + curve_name + b" " + base64.b64encode( serialization._ssh_write_string(b"ecdsa-sha2-" + curve_name) + serialization._ssh_write_string(curve_name) + serialization._ssh_write_string(public_numbers.encode_point()) )
Example #27
Source File: test_transport.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def test_disconnectKEX_ECDH_REPLYBadSignature(self): """ Test that KEX_ECDH_REPLY disconnects if the signature is bad. """ kexmsg = ( b"\xAA" * 16 + common.NS(b'ecdh-sha2-nistp256') + common.NS(b'ssh-rsa') + common.NS(b'aes256-ctr') + common.NS(b'aes256-ctr') + common.NS(b'hmac-sha1') + common.NS(b'hmac-sha1') + common.NS(b'none') + common.NS(b'none') + common.NS(b'') + common.NS(b'') + b'\x00' + b'\x00\x00\x00\x00') self.proto.ssh_KEXINIT(kexmsg) self.proto.dataReceived(b"SSH-2.0-OpenSSH\r\n") self.proto.ecPriv = ec.generate_private_key(ec.SECP256R1(), default_backend()) self.proto.ecPub = self.proto.ecPriv.public_key() # Generate the private key thisPriv = ec.generate_private_key(ec.SECP256R1(), default_backend()) # Get the public key thisPub = thisPriv.public_key() encPub = thisPub.public_numbers().encode_point() self.proto.curve = ec.SECP256R1() self.proto.kexAlg = b'ecdh-sha2-nistp256' self.proto._ssh_KEX_ECDH_REPLY( common.NS(MockFactory().getPublicKeys()[b'ssh-rsa'].blob()) + common.NS(encPub) + common.NS(b'bad-signature')) self.checkDisconnected(transport.DISCONNECT_KEY_EXCHANGE_FAILED)
Example #28
Source File: test_transport.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def test_disconnectKEX_ECDH_REPLYBadSignature(self): """ Test that KEX_ECDH_REPLY disconnects if the signature is bad. """ kexmsg = ( b"\xAA" * 16 + common.NS(b'ecdh-sha2-nistp256') + common.NS(b'ssh-rsa') + common.NS(b'aes256-ctr') + common.NS(b'aes256-ctr') + common.NS(b'hmac-sha1') + common.NS(b'hmac-sha1') + common.NS(b'none') + common.NS(b'none') + common.NS(b'') + common.NS(b'') + b'\x00' + b'\x00\x00\x00\x00') self.proto.ssh_KEXINIT(kexmsg) self.proto.dataReceived(b"SSH-2.0-OpenSSH\r\n") self.proto.ecPriv = ec.generate_private_key(ec.SECP256R1(), default_backend()) self.proto.ecPub = self.proto.ecPriv.public_key() # Generate the private key thisPriv = ec.generate_private_key(ec.SECP256R1(), default_backend()) # Get the public key thisPub = thisPriv.public_key() encPub = thisPub.public_numbers().encode_point() self.proto.curve = ec.SECP256R1() self.proto.kexAlg = b'ecdh-sha2-nistp256' self.proto._ssh_KEX_ECDH_REPLY( common.NS(MockFactory().getPublicKeys()[b'ssh-rsa'].blob()) + common.NS(encPub) + common.NS(b'bad-signature')) self.checkDisconnected(transport.DISCONNECT_KEY_EXCHANGE_FAILED)
Example #29
Source File: serialization.py From oss-ftp with MIT License | 5 votes |
def _load_ssh_ecdsa_public_key(expected_key_type, decoded_data, backend): curve_name, rest = _read_next_string(decoded_data) data, rest = _read_next_string(rest) if expected_key_type != b"ecdsa-sha2-" + curve_name: raise ValueError( 'Key header and key body contain different key type values.' ) if rest: raise ValueError('Key body contains extra bytes.') curve = { b"nistp256": ec.SECP256R1, b"nistp384": ec.SECP384R1, b"nistp521": ec.SECP521R1, }[curve_name]() if six.indexbytes(data, 0) != 4: raise NotImplementedError( "Compressed elliptic curve points are not supported" ) # key_size is in bits, and sometimes it's not evenly divisible by 8, so we # add 7 to round up the number of bytes. if len(data) != 1 + 2 * ((curve.key_size + 7) // 8): raise ValueError("Malformed key bytes") x = utils.int_from_bytes( data[1:1 + (curve.key_size + 7) // 8], byteorder='big' ) y = utils.int_from_bytes( data[1 + (curve.key_size + 7) // 8:], byteorder='big' ) return ec.EllipticCurvePublicNumbers(x, y, curve).public_key(backend)
Example #30
Source File: test_kex.py From python-hpedockerplugin with Apache License 2.0 | 5 votes |
def dummy_generate_key_pair(obj): private_key_value = 94761803665136558137557783047955027733968423115106677159790289642479432803037 public_key_numbers = "042bdab212fa8ba1b7c843301682a4db424d307246c7e1e6083c41d9ca7b098bf30b3d63e2ec6278488c135360456cc054b3444ecc45998c08894cbc1370f5f989" public_key_numbers_obj = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256R1(), unhexlify(public_key_numbers)) obj.P = ec.EllipticCurvePrivateNumbers(private_value=private_key_value, public_numbers=public_key_numbers_obj).private_key(default_backend()) if obj.transport.server_mode: obj.Q_S = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256R1(), unhexlify(public_key_numbers)).public_key(default_backend()) return obj.Q_C = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256R1(), unhexlify(public_key_numbers)).public_key(default_backend())