Python cryptography.hazmat.primitives.asymmetric.ec.SECP384R1 Examples

The following are 30 code examples of cryptography.hazmat.primitives.asymmetric.ec.SECP384R1(). 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: ssh.py    From learn_python3_spider with MIT License 6 votes vote down vote up
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 #2
Source File: ssh.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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: ssh.py    From quickstart-redhat-openshift with Apache License 2.0 6 votes vote down vote up
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 #4
Source File: serialization.py    From quickstart-git2s3 with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: cryptography_backend.py    From python-jose with MIT License 6 votes vote down vote up
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 #6
Source File: enc_advanced.py    From XFLTReaT with MIT License 6 votes vote down vote up
def __init__(self):
		super(Encryption_module, self).__init__()
		self.cmh_struct_encryption  = {
			# num : [string to look for, function, server(1) or client(0), return on success, return on failure]
			# return value meanings: True  - module continues
			#						 False - module thread terminates
			# in case of Stateless modules, the whole module terminates if the return value is False
			0  : ["XFLT>ECDHd1", 	self.encryption_step_1, 1, True, False, True],
			1  : ["XFLT>ECDHd2", 	self.encryption_step_2, 0, True, False, False],
			2  : ["XFLT>ECDHd3", 	self.encryption_step_3, 1, True, False, True],
			3  : ["XFLT>ECDHd4", 	self.encryption_step_4, 0, True, False, False],
			4  : ["XFLT>ECDHd5", 	self.encryption_step_5, 1, True, False, True],
		}

		self.client_step_count = 2
		self.server_step_count = 3

		self.server_public_key_file = "misc/public_key_advanced.pem"
		self.server_private_key_file = "misc/private_key_advanced.pem"
		self.curve = ec.SECP384R1()

		return 
Example #7
Source File: ssh.py    From teleport with Apache License 2.0 6 votes vote down vote up
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: ssh.py    From teleport with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: serialization.py    From teleport with Apache License 2.0 6 votes vote down vote up
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: serialization.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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 #11
Source File: signature_handler.py    From ontology-python-sdk with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #12
Source File: test_EC.py    From python-jose with MIT License 5 votes vote down vote up
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 #13
Source File: jwk.py    From jwcrypto with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #14
Source File: ecc.py    From synapse with Apache License 2.0 5 votes vote down vote up
def generate():
        '''
        Generate a new ECC PriKey instance.

        Returns:
            PriKey: A new PriKey instance.
        '''
        return PriKey(c_ec.generate_private_key(
            c_ec.SECP384R1(),
            default_backend()
        )) 
Example #15
Source File: tls.py    From dcos-e2e with Apache License 2.0 5 votes vote down vote up
def generate_ec_private_key(curve=None):
    """
    Generate EC private key.

    Args:
        curve (ec.EllipticCurve): EC if not provided SECP384R1 used.

    Return:
        ec.EllipticCurvePrivateKey
    """
    curve = ec.SECP384R1() if curve is None else curve
    return ec.generate_private_key(
        curve=curve,
        backend=cryptography_default_backend
        ) 
Example #16
Source File: tls.py    From dcos-e2e with Apache License 2.0 5 votes vote down vote up
def generate_ec_private_key(curve=None):
    """
    Generate EC private key.

    Args:
        curve (ec.EllipticCurve): EC if not provided SECP384R1 used.

    Return:
        ec.EllipticCurvePrivateKey
    """
    curve = ec.SECP384R1() if curve is None else curve
    return ec.generate_private_key(
        curve=curve,
        backend=cryptography_default_backend
        ) 
Example #17
Source File: test_f_crypto.py    From aws-encryption-sdk-python with Apache License 2.0 5 votes vote down vote up
def test_signer_key_bytes_cycle():
    key = ec.generate_private_key(curve=ec.SECP384R1, backend=default_backend())
    signer = Signer(algorithm=aws_encryption_sdk.Algorithm.AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, key=key)
    key_bytes = signer.key_bytes()
    new_signer = Signer.from_key_bytes(
        algorithm=aws_encryption_sdk.Algorithm.AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, key_bytes=key_bytes
    )
    assert new_signer.key.private_numbers().private_value == signer.key.private_numbers().private_value 
Example #18
Source File: backend.py    From quickstart-git2s3 with Apache License 2.0 5 votes vote down vote up
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 #19
Source File: backend.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
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 #20
Source File: test_crypto_elliptic_curve.py    From aws-encryption-sdk-python with Apache License 2.0 5 votes vote down vote up
def test_ecc_curve_not_in_cryptography():
    """If this test fails, then this pull or similar has gone through
        and this library should be updated to use the ECC curve
        parameters from cryptography.
        https://github.com/pyca/cryptography/pull/2499
    """
    assert not hasattr(ec.SECP384R1, "a") 
Example #21
Source File: crypto.py    From fabric-sdk-py with Apache License 2.0 5 votes vote down vote up
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 #22
Source File: test.py    From signxml with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.example_xml_files = (os.path.join(os.path.dirname(__file__), "example.xml"),
                                  os.path.join(os.path.dirname(__file__), "example2.xml"))
        self.keys = dict(hmac=b"secret",
                         rsa=rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()),
                         dsa=dsa.generate_private_key(key_size=1024, backend=default_backend()),
                         ecdsa=ec.generate_private_key(curve=ec.SECP384R1(), backend=default_backend())) 
Example #23
Source File: test_crypto_elliptic_curve.py    From aws-encryption-sdk-python with Apache License 2.0 5 votes vote down vote up
def test_ecc_decode_compressed_point_infinity():
    with pytest.raises(NotSupportedError) as excinfo:
        _ecc_decode_compressed_point(curve=ec.SECP384R1(), compressed_point=b"")

    excinfo.match(r"Points at infinity are not allowed") 
Example #24
Source File: test_crypto_elliptic_curve.py    From aws-encryption-sdk-python with Apache License 2.0 5 votes vote down vote up
def test_ecc_decode_compressed_point_prime():
    x, y = _ecc_decode_compressed_point(curve=ec.SECP384R1(), compressed_point=VALUES["ecc_compressed_point"])
    numbers = VALUES["ecc_private_key_prime"].public_key().public_numbers()
    assert x == numbers.x
    assert y == numbers.y 
Example #25
Source File: test_crypto_elliptic_curve.py    From aws-encryption-sdk-python with Apache License 2.0 5 votes vote down vote up
def test_ecc_decode_compressed_point_prime_characteristic_two(patch_pow):
    patch_pow.return_value = 1
    _, y = _ecc_decode_compressed_point(curve=ec.SECP384R1(), compressed_point=VALUES["ecc_compressed_point"])
    assert y == 1 
Example #26
Source File: serialization.py    From oss-ftp with MIT License 5 votes vote down vote up
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 #27
Source File: backend.py    From teleport with Apache License 2.0 5 votes vote down vote up
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 #28
Source File: utils.py    From lemur with Apache License 2.0 4 votes vote down vote up
def generate_private_key(key_type):
    """
    Generates a new private key based on key_type.

    Valid key types: RSA2048, RSA4096', 'ECCPRIME192V1', 'ECCPRIME256V1', 'ECCSECP192R1',
        'ECCSECP224R1', 'ECCSECP256R1', 'ECCSECP384R1', 'ECCSECP521R1', 'ECCSECP256K1',
        'ECCSECT163K1', 'ECCSECT233K1', 'ECCSECT283K1', 'ECCSECT409K1', 'ECCSECT571K1',
        'ECCSECT163R2', 'ECCSECT233R1', 'ECCSECT283R1', 'ECCSECT409R1', 'ECCSECT571R2'

    :param key_type:
    :return:
    """

    _CURVE_TYPES = {
        "ECCPRIME192V1": ec.SECP192R1(),
        "ECCPRIME256V1": ec.SECP256R1(),
        "ECCSECP192R1": ec.SECP192R1(),
        "ECCSECP224R1": ec.SECP224R1(),
        "ECCSECP256R1": ec.SECP256R1(),
        "ECCSECP384R1": ec.SECP384R1(),
        "ECCSECP521R1": ec.SECP521R1(),
        "ECCSECP256K1": ec.SECP256K1(),
        "ECCSECT163K1": ec.SECT163K1(),
        "ECCSECT233K1": ec.SECT233K1(),
        "ECCSECT283K1": ec.SECT283K1(),
        "ECCSECT409K1": ec.SECT409K1(),
        "ECCSECT571K1": ec.SECT571K1(),
        "ECCSECT163R2": ec.SECT163R2(),
        "ECCSECT233R1": ec.SECT233R1(),
        "ECCSECT283R1": ec.SECT283R1(),
        "ECCSECT409R1": ec.SECT409R1(),
        "ECCSECT571R2": ec.SECT571R1(),
    }

    if key_type not in CERTIFICATE_KEY_TYPES:
        raise Exception(
            "Invalid key type: {key_type}. Supported key types: {choices}".format(
                key_type=key_type, choices=",".join(CERTIFICATE_KEY_TYPES)
            )
        )

    if "RSA" in key_type:
        key_size = int(key_type[3:])
        return rsa.generate_private_key(
            public_exponent=65537, key_size=key_size, backend=default_backend()
        )
    elif "ECC" in key_type:
        return ec.generate_private_key(
            curve=_CURVE_TYPES[key_type], backend=default_backend()
        ) 
Example #29
Source File: backend.py    From quickstart-redhat-openshift with Apache License 2.0 4 votes vote down vote up
def _openssh_public_key_bytes(self, key):
        if isinstance(key, rsa.RSAPublicKey):
            public_numbers = key.public_numbers()
            return b"ssh-rsa " + base64.b64encode(
                ssh._ssh_write_string(b"ssh-rsa") +
                ssh._ssh_write_mpint(public_numbers.e) +
                ssh._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(
                ssh._ssh_write_string(b"ssh-dss") +
                ssh._ssh_write_mpint(parameter_numbers.p) +
                ssh._ssh_write_mpint(parameter_numbers.q) +
                ssh._ssh_write_mpint(parameter_numbers.g) +
                ssh._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"
                )

            point = key.public_bytes(
                serialization.Encoding.X962,
                serialization.PublicFormat.UncompressedPoint
            )
            return b"ecdsa-sha2-" + curve_name + b" " + base64.b64encode(
                ssh._ssh_write_string(b"ecdsa-sha2-" + curve_name) +
                ssh._ssh_write_string(curve_name) +
                ssh._ssh_write_string(point)
            ) 
Example #30
Source File: backend.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _openssh_public_key_bytes(self, key):
        if isinstance(key, rsa.RSAPublicKey):
            public_numbers = key.public_numbers()
            return b"ssh-rsa " + base64.b64encode(
                ssh._ssh_write_string(b"ssh-rsa") +
                ssh._ssh_write_mpint(public_numbers.e) +
                ssh._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(
                ssh._ssh_write_string(b"ssh-dss") +
                ssh._ssh_write_mpint(parameter_numbers.p) +
                ssh._ssh_write_mpint(parameter_numbers.q) +
                ssh._ssh_write_mpint(parameter_numbers.g) +
                ssh._ssh_write_mpint(public_numbers.y)
            )
        elif isinstance(key, ed25519.Ed25519PublicKey):
            raw_bytes = key.public_bytes(serialization.Encoding.Raw,
                                         serialization.PublicFormat.Raw)
            return b"ssh-ed25519 " + base64.b64encode(
                ssh._ssh_write_string(b"ssh-ed25519") +
                ssh._ssh_write_string(raw_bytes)
            )
        elif 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"
                )

            point = key.public_bytes(
                serialization.Encoding.X962,
                serialization.PublicFormat.UncompressedPoint
            )
            return b"ecdsa-sha2-" + curve_name + b" " + base64.b64encode(
                ssh._ssh_write_string(b"ecdsa-sha2-" + curve_name) +
                ssh._ssh_write_string(curve_name) +
                ssh._ssh_write_string(point)
            )
        else:
            raise ValueError(
                "OpenSSH encoding is not supported for this key type"
            )