Python cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey() Examples

The following are 22 code examples of cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey(). 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: keys.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def type(self):
        """
        Return the type of the object we wrap.  Currently this can only be
        'RSA', 'DSA', or 'EC'.

        @rtype: L{str}
        @raises RuntimeError: If the object type is unknown.
        """
        if isinstance(
                self._keyObject, (rsa.RSAPublicKey, rsa.RSAPrivateKey)):
            return 'RSA'
        elif isinstance(
                self._keyObject, (dsa.DSAPublicKey, dsa.DSAPrivateKey)):
            return 'DSA'
        elif isinstance(
                self._keyObject, (ec.EllipticCurvePublicKey, ec.EllipticCurvePrivateKey)):
            return 'EC'
        else:
            raise RuntimeError(
                'unknown type of object: %r' % (self._keyObject,)) 
Example #2
Source File: tls.py    From dcos-e2e with Apache License 2.0 6 votes vote down vote up
def generate_valid_root_ca_cert_pem(private_key):
    """
    Helper to create and serialize root CA cert.

    Args:
        private_key (rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey): Key that
            should be used for signing the certificate.

    Return:
        PEM text representing serialized certificate.
    """
    return serialize_cert_to_pem(
        sign_cert_builder(
            ca_cert_builder(
                private_key.public_key(),
            ),
            private_key
            )
        ) 
Example #3
Source File: keys.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def type(self):
        """
        Return the type of the object we wrap.  Currently this can only be
        'RSA', 'DSA', or 'EC'.

        @rtype: L{str}
        @raises RuntimeError: If the object type is unknown.
        """
        if isinstance(
                self._keyObject, (rsa.RSAPublicKey, rsa.RSAPrivateKey)):
            return 'RSA'
        elif isinstance(
                self._keyObject, (dsa.DSAPublicKey, dsa.DSAPrivateKey)):
            return 'DSA'
        elif isinstance(
                self._keyObject, (ec.EllipticCurvePublicKey, ec.EllipticCurvePrivateKey)):
            return 'EC'
        else:
            raise RuntimeError(
                'unknown type of object: %r' % (self._keyObject,)) 
Example #4
Source File: test_create_key.py    From sros2 with Apache License 2.0 5 votes vote down vote up
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 #5
Source File: runtime_credentials.py    From calvin-base with Apache License 2.0 5 votes vote down vote up
def sign_data(self, data):
        from OpenSSL import crypto
        from cryptography.hazmat.backends import default_backend
        from cryptography.hazmat.primitives import hashes
        from cryptography.hazmat.primitives.asymmetric import dsa, rsa
        from cryptography.hazmat.primitives.asymmetric import ec
        from cryptography.hazmat.primitives.serialization import load_pem_private_key
        private_key_str = self.get_private_key()
#       The pyOpenSSL sign operation seems broken and corrupts memory, atleast for EC, so let's use
#       the cryptography package instead
#        try:
#            private_key = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM,
#                                                        private_key_str, '')
#            signature = OpenSSL.crypto.sign(private_key,
#                                            data,
#                                            "sha256")
#        except Exception as err:
#            _log.error("Failed to sign data, err={}".format(err))
#            raise
        try:
            private_key = load_pem_private_key(private_key_str, password=None, backend=default_backend())
            if isinstance(private_key, ec.EllipticCurvePrivateKey):
                signature = private_key.sign(data, ec.ECDSA(hashes.SHA256()))
            elif isinstance(private_key, rsa.RSAPrivateKey):
                signature = sign_with_rsa_key(private_key, message)
            elif isinstance(private_key, dsa.DSAPrivateKey):
                signature = sign_with_dsa_key(private_key, message)
            else:
                raise TypeError
        except Exception as err:
            _log.error("Failed to sign data, err={}".format(err))
            raise
        return signature 
Example #6
Source File: ecc.py    From synapse with Apache License 2.0 5 votes vote down vote up
def __init__(self, priv):
        self.priv = priv  # type: c_ec.EllipticCurvePrivateKey
        self.publ = PubKey(self.priv.public_key()) 
Example #7
Source File: ecdsa_sign.py    From jws with Apache License 2.0 5 votes vote down vote up
def __init__(self, priv_key, algorithm):
    """Constructor for EcdsaSign.

    Args:
      priv_key: ec.EllipticCurvePrivateKey, the Ecdsa private key.
      algorithm: string, Ecdsa algorithm as defined at
               https://tools.ietf.org/html/rfc7518#section-3.1.
    Raises:
      TypeError: if the public key is not an instance of
      ec.EllipticCurvePublicKey.
      UnsupportedAlgorithm: if the algorithm is not supported.
    """
    if not isinstance(priv_key, ec.EllipticCurvePrivateKey):
      raise TypeError(
          "The private key must be an instance of ec.EllipticCurvePrivateKey")
    self.priv_key = priv_key
    curve_name = ""
    if algorithm == "ES256":
      self.hash = hashes.SHA256()
      curve_name = "secp256r1"
    elif algorithm == "ES384":
      self.hash = hashes.SHA384()
      curve_name = "secp384r1"
    elif algorithm == "ES512":
      self.hash = hashes.SHA512()
      curve_name = "secp521r1"
    else:
      raise exceptions.UnsupportedAlgorithm(
          "Unknown algorithm : %s" % (algorithm))
    # In Ecdsa, both the key and the algorithm define the curve. Therefore, we
    # must cross check them to make sure they're the same.
    if curve_name != priv_key.public_key().curve.name:
      raise exceptions.UnsupportedAlgorithm(
          "The curve in private key %s and in algorithm % don't match" %
          (priv_key.public_key().curve.name, curve_name))
    self.algorithm = algorithm 
Example #8
Source File: tls.py    From dcos-e2e with Apache License 2.0 5 votes vote down vote up
def serialize_key_to_pem(key):
    """
    Serialize private key to OpenSSL format with PEM encoding.

    Args:
        key (rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey): Key to serialize

    Returns:
        PEM text representing serialized key.
    """
    return key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption()
        ).decode('utf-8') 
Example #9
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 #10
Source File: tls.py    From dcos-e2e with Apache License 2.0 5 votes vote down vote up
def serialize_key_to_pem(key):
    """
    Serialize private key to OpenSSL format with PEM encoding.

    Args:
        key (rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey): Key to serialize

    Returns:
        PEM text representing serialized key.
    """
    return key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption()
        ).decode('utf-8') 
Example #11
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 #12
Source File: jwk.py    From jwcrypto with GNU Lesser General Public License v3.0 5 votes vote down vote up
def import_from_pyca(self, key):
        if isinstance(key, rsa.RSAPrivateKey):
            self._import_pyca_pri_rsa(key)
        elif isinstance(key, rsa.RSAPublicKey):
            self._import_pyca_pub_rsa(key)
        elif isinstance(key, ec.EllipticCurvePrivateKey):
            self._import_pyca_pri_ec(key)
        elif isinstance(key, ec.EllipticCurvePublicKey):
            self._import_pyca_pub_ec(key)
        elif isinstance(key, (Ed25519PrivateKey, Ed448PrivateKey)):
            self._import_pyca_pri_okp(key)
        elif isinstance(key, (Ed25519PublicKey, Ed448PublicKey)):
            self._import_pyca_pub_okp(key)
        else:
            raise InvalidJWKValue('Unknown key object %r' % key) 
Example #13
Source File: tests_command_init_ca.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_ecc(self):
        with self.assertSignal(pre_create_ca) as pre, self.assertSignal(post_create_ca) as post:
            out, err = self.init_ca(
                algorithm=hashes.SHA1(),
                key_type='ECC',
                key_size=1024,
                expires=self.expires(720),
                pathlen=3,
                issuer_url='http://issuer.ca.example.com',
                issuer_alt_name={'value': ['http://ian.ca.example.com']},
                crl_url=['http://crl.example.com'],
                ocsp_url='http://ocsp.example.com',
                ca_issuer_url='http://ca.issuer.ca.example.com',
                permit_name=['DNS:.com'],
                exclude_name=['DNS:.net'],
            )
        self.assertTrue(pre.called)
        self.assertEqual(out, '')
        self.assertEqual(err, '')
        ca = CertificateAuthority.objects.first()
        self.assertPostCreateCa(post, ca)
        self.assertIsInstance(ca.key(None), ec.EllipticCurvePrivateKey)
        self.assertEqual(ca.name_constraints, NameConstraints({'value': {
            'permitted': ['DNS:.com'],
            'excluded': ['DNS:.net'],
        }})) 
Example #14
Source File: test_es256.py    From google-auth-library-python with Apache License 2.0 5 votes vote down vote up
def test_from_service_account_file(self):
        signer = es256.ES256Signer.from_service_account_file(SERVICE_ACCOUNT_JSON_FILE)

        assert signer.key_id == SERVICE_ACCOUNT_INFO[base._JSON_FILE_PRIVATE_KEY_ID]
        assert isinstance(signer._key, ec.EllipticCurvePrivateKey) 
Example #15
Source File: test_es256.py    From google-auth-library-python with Apache License 2.0 5 votes vote down vote up
def test_from_service_account_info(self):
        signer = es256.ES256Signer.from_service_account_info(SERVICE_ACCOUNT_INFO)

        assert signer.key_id == SERVICE_ACCOUNT_INFO[base._JSON_FILE_PRIVATE_KEY_ID]
        assert isinstance(signer._key, ec.EllipticCurvePrivateKey) 
Example #16
Source File: test_es256.py    From google-auth-library-python with Apache License 2.0 5 votes vote down vote up
def test_from_string_pkcs1_unicode(self):
        key_bytes = _helpers.from_bytes(PKCS1_KEY_BYTES)
        signer = es256.ES256Signer.from_string(key_bytes)
        assert isinstance(signer, es256.ES256Signer)
        assert isinstance(signer._key, ec.EllipticCurvePrivateKey) 
Example #17
Source File: test_es256.py    From google-auth-library-python with Apache License 2.0 5 votes vote down vote up
def test_from_string_pkcs1(self):
        signer = es256.ES256Signer.from_string(PKCS1_KEY_BYTES)
        assert isinstance(signer, es256.ES256Signer)
        assert isinstance(signer._key, ec.EllipticCurvePrivateKey) 
Example #18
Source File: jwa.py    From jwcrypto with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #19
Source File: keys.py    From learn_python3_spider with MIT License 4 votes vote down vote up
def data(self):
        """
        Return the values of the public key as a dictionary.

        @rtype: L{dict}
        """
        if isinstance(self._keyObject, rsa.RSAPublicKey):
            numbers = self._keyObject.public_numbers()
            return {
                "n": numbers.n,
                "e": numbers.e,
            }
        elif isinstance(self._keyObject, rsa.RSAPrivateKey):
            numbers = self._keyObject.private_numbers()
            return {
                "n": numbers.public_numbers.n,
                "e": numbers.public_numbers.e,
                "d": numbers.d,
                "p": numbers.p,
                "q": numbers.q,
                # Use a trick: iqmp is q^-1 % p, u is p^-1 % q
                "u": rsa.rsa_crt_iqmp(numbers.q, numbers.p),
            }
        elif isinstance(self._keyObject, dsa.DSAPublicKey):
            numbers = self._keyObject.public_numbers()
            return {
                "y": numbers.y,
                "g": numbers.parameter_numbers.g,
                "p": numbers.parameter_numbers.p,
                "q": numbers.parameter_numbers.q,
            }
        elif isinstance(self._keyObject, dsa.DSAPrivateKey):
            numbers = self._keyObject.private_numbers()
            return {
                "x": numbers.x,
                "y": numbers.public_numbers.y,
                "g": numbers.public_numbers.parameter_numbers.g,
                "p": numbers.public_numbers.parameter_numbers.p,
                "q": numbers.public_numbers.parameter_numbers.q,
            }
        elif isinstance(self._keyObject, ec.EllipticCurvePublicKey):
            numbers = self._keyObject.public_numbers()
            return {
                "x": numbers.x,
                "y": numbers.y,
                "curve": self.sshType(),
            }
        elif isinstance(self._keyObject, ec.EllipticCurvePrivateKey):
            numbers = self._keyObject.private_numbers()
            return {
                "x": numbers.public_numbers.x,
                "y": numbers.public_numbers.y,
                "privateValue": numbers.private_value,
                "curve": self.sshType(),
            }

        else:
            raise RuntimeError("Unexpected key type: %s" % (self._keyObject,)) 
Example #20
Source File: cleartext_jwk_set_reader.py    From jws with Apache License 2.0 4 votes vote down vote up
def from_cryptography_key(cls, key, algorithm, kid=""):
    """Transform cryptography's key to Jwk key.

    As cryptography's key doesn't specify the full algorithm to use (e.g. a RSA
    key doesn't specify which hash function should be used), the caller has to
    specify what algorithm that it would use the key for.

    Args:
      key: rsa.RSAPrivateKey, rsa.RSAPublicKey, ec.EllipticCurvePrivateKey or
        ec.EllipticCurvePublicKey
      algorithm: string, RSA or ECDSA algorithm as defined at
        https://tools.ietf.org/html/rfc7518#section-3.1.
      kid: string, Key ID as defined at
        https://tools.ietf.org/html/rfc7515#section-4.1.4.

    Raises:
      UnsupportedAlgorithm: if the algorithm is not supported or cryptography
      key has error.

    Returns:
      A JwkSet.
    """
    rsa_algorithms = ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512"]
    ecdsa_algorithms = ["ES256", "ES384", "ES512"]

    if algorithm in rsa_algorithms:
      if isinstance(key, rsa.RSAPrivateKey):
        return JwkSet([Jwk("RSA", kid, algorithm, None, key, key.public_key())])
      elif isinstance(key, rsa.RSAPublicKey):
        return JwkSet([Jwk("RSA", kid, algorithm, None, None, key)])
      else:
        raise exceptions.UnsupportedAlgorithm(
            "Unsupported mismatch between algorithm: %s and cryptography key:%s"
            % (algorithm, key))
    elif algorithm in ecdsa_algorithms:
      if isinstance(key, ec.EllipticCurvePrivateKey):
        return JwkSet([Jwk("EC", kid, algorithm, None, key, key.public_key())])
      elif isinstance(key, ec.EllipticCurvePublicKey):
        return JwkSet([Jwk("EC", kid, algorithm, None, None, key)])
      else:
        raise exceptions.UnsupportedAlgorithm(
            "Unsupported mismatch between algorithm: %s and cryptography key:%s"
            % (algorithm, key))
    else:
      raise exceptions.UnsupportedAlgorithm(
          "Unknown algorithm: %s" % (algorithm)) 
Example #21
Source File: cleartext_jwk_set_reader.py    From jws with Apache License 2.0 4 votes vote down vote up
def from_pem(cls, pem_key, algorithm, kid=""):
    """Parses PEM key and transformat it to Jwk key.

    As PEM key doesn't specify the full algorithm to use (e.g. a RSA key doesn't
    specify which hash function should be used), the caller has to specify what
    algorithm that it would use the key for.
    Args:
      pem_key: bytes, RSA or ECDSA key in PEM format.
      algorithm: string, RSA or ECDSA algorithm as defined at
        https://tools.ietf.org/html/rfc7518#section-3.1.
      kid: string, Key ID as defined at
        https://tools.ietf.org/html/rfc7515#section-4.1.4.

    Raises:
      UnsupportedAlgorithm: if the algorithm is not supported or pem_key is
      error.
    """
    if algorithm not in [
        "RS256", "RS384", "RS512", "ES256", "ES384", "ES512", "PS256", "PS384",
        "PS512"
    ]:
      raise exceptions.UnsupportedAlgorithm(
          "Unknown algorithm: %s" % (algorithm))
    key_type = ""
    key = ""
    # Try to parse it as private key.
    try:
      key = load_pem_private_key(
          pem_key, None, backend=backends.default_backend())
    except (ValueError, TypeError, exceptions.UnsupportedAlgorithm) as ignored:
      # If not succeeded, try to parse it as public key.
      try:
        key = load_pem_public_key(pem_key, backend=backends.default_backend())
      except (ValueError, TypeError, exceptions.UnsupportedAlgorithm) as e:
        raise exceptions.UnsupportedAlgorithm("Pem key parsing error: %s" % (e))
    if isinstance(key, rsa.RSAPrivateKey):
      return JwkSet([Jwk("RSA", kid, algorithm, None, key, key.public_key())])
    elif isinstance(key, rsa.RSAPublicKey):
      return JwkSet([Jwk("RSA", kid, algorithm, None, None, key)])
    elif isinstance(key, ec.EllipticCurvePrivateKey):
      return JwkSet([Jwk("EC", kid, algorithm, None, key, key.public_key())])
    elif isinstance(key, ec.EllipticCurvePublicKey):
      return JwkSet([Jwk("EC", kid, algorithm, None, None, key)])
    else:
      raise exceptions.UnsupportedAlgorithm(
          "Unknown supported key pem: %s" % (e)) 
Example #22
Source File: keys.py    From Safejumper-for-Desktop with GNU General Public License v2.0 4 votes vote down vote up
def data(self):
        """
        Return the values of the public key as a dictionary.

        @rtype: L{dict}
        """
        if isinstance(self._keyObject, rsa.RSAPublicKey):
            numbers = self._keyObject.public_numbers()
            return {
                "n": numbers.n,
                "e": numbers.e,
            }
        elif isinstance(self._keyObject, rsa.RSAPrivateKey):
            numbers = self._keyObject.private_numbers()
            return {
                "n": numbers.public_numbers.n,
                "e": numbers.public_numbers.e,
                "d": numbers.d,
                "p": numbers.p,
                "q": numbers.q,
                # Use a trick: iqmp is q^-1 % p, u is p^-1 % q
                "u": rsa.rsa_crt_iqmp(numbers.q, numbers.p),
            }
        elif isinstance(self._keyObject, dsa.DSAPublicKey):
            numbers = self._keyObject.public_numbers()
            return {
                "y": numbers.y,
                "g": numbers.parameter_numbers.g,
                "p": numbers.parameter_numbers.p,
                "q": numbers.parameter_numbers.q,
            }
        elif isinstance(self._keyObject, dsa.DSAPrivateKey):
            numbers = self._keyObject.private_numbers()
            return {
                "x": numbers.x,
                "y": numbers.public_numbers.y,
                "g": numbers.public_numbers.parameter_numbers.g,
                "p": numbers.public_numbers.parameter_numbers.p,
                "q": numbers.public_numbers.parameter_numbers.q,
            }
        elif isinstance(self._keyObject, ec.EllipticCurvePublicKey):
            numbers = self._keyObject.public_numbers()
            return {
                "x": numbers.x,
                "y": numbers.y,
                "curve": self.sshType(),
            }
        elif isinstance(self._keyObject, ec.EllipticCurvePrivateKey):
            numbers = self._keyObject.private_numbers()
            return {
                "x": numbers.public_numbers.x,
                "y": numbers.public_numbers.y,
                "privateValue": numbers.private_value,
                "curve": self.sshType(),
            }

        else:
            raise RuntimeError("Unexpected key type: %s" % (self._keyObject,))