Python cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKey() Examples

The following are 10 code examples of cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKey(). 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.dsa , or try the search function .
Example #1
Source File: crypto.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def from_cryptography_key(cls, crypto_key):
        """
        Construct based on a ``cryptography`` *crypto_key*.

        :param crypto_key: A ``cryptography`` key.
        :type crypto_key: One of ``cryptography``'s `key interfaces`_.

        :rtype: PKey

        .. versionadded:: 16.1.0
        """
        pkey = cls()
        if not isinstance(crypto_key, (rsa.RSAPublicKey, rsa.RSAPrivateKey,
                                       dsa.DSAPublicKey, dsa.DSAPrivateKey)):
            raise TypeError("Unsupported key type")

        pkey._pkey = crypto_key._evp_pkey
        if isinstance(crypto_key, (rsa.RSAPublicKey, dsa.DSAPublicKey)):
            pkey._only_public = True
        pkey._initialized = True
        return pkey 
Example #2
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 #3
Source File: crypto.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def from_cryptography_key(cls, crypto_key):
        """
        Construct based on a ``cryptography`` *crypto_key*.

        :param crypto_key: A ``cryptography`` key.
        :type crypto_key: One of ``cryptography``'s `key interfaces`_.

        :rtype: PKey

        .. versionadded:: 16.1.0
        """
        pkey = cls()
        if not isinstance(crypto_key, (rsa.RSAPublicKey, rsa.RSAPrivateKey,
                                       dsa.DSAPublicKey, dsa.DSAPrivateKey)):
            raise TypeError("Unsupported key type")

        pkey._pkey = crypto_key._evp_pkey
        if isinstance(crypto_key, (rsa.RSAPublicKey, dsa.DSAPublicKey)):
            pkey._only_public = True
        pkey._initialized = True
        return pkey 
Example #4
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 #5
Source File: crypto.py    From pyopenssl with Apache License 2.0 6 votes vote down vote up
def from_cryptography_key(cls, crypto_key):
        """
        Construct based on a ``cryptography`` *crypto_key*.

        :param crypto_key: A ``cryptography`` key.
        :type crypto_key: One of ``cryptography``'s `key interfaces`_.

        :rtype: PKey

        .. versionadded:: 16.1.0
        """
        pkey = cls()
        if not isinstance(crypto_key, (rsa.RSAPublicKey, rsa.RSAPrivateKey,
                                       dsa.DSAPublicKey, dsa.DSAPrivateKey)):
            raise TypeError("Unsupported key type")

        pkey._pkey = crypto_key._evp_pkey
        if isinstance(crypto_key, (rsa.RSAPublicKey, dsa.DSAPublicKey)):
            pkey._only_public = True
        pkey._initialized = True
        return pkey 
Example #6
Source File: models.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def cache_crls(self, password=None, algorithm=None):
        password = password or self.get_password()
        ca_key = self.key(password)
        if isinstance(ca_key, dsa.DSAPrivateKey) and algorithm is None:
            algorithm = hashes.SHA1()

        for name, config in ca_settings.CA_CRL_PROFILES.items():
            overrides = config.get('OVERRIDES', {}).get(self.serial, {})

            if overrides.get('skip'):
                continue

            algorithm = algorithm or parse_hash_algorithm(overrides.get('algorithm', config.get('algorithm')))
            expires = overrides.get('expires', config.get('expires', 86400))
            scope = overrides.get('scope', config.get('scope'))
            full_name = overrides.get('full_name', config.get('full_name'))
            relative_name = overrides.get('relative_name', config.get('relative_name'))
            encodings = overrides.get('encodings', config.get('encodings', ['DER', ]))
            crl = None  # only compute crl when it is actually needed

            for encoding in encodings:
                encoding = parse_encoding(encoding)
                cache_key = get_crl_cache_key(self.serial, algorithm, encoding, scope=scope)

                if expires >= 600:  # pragma: no branch
                    # for longer expiries we substract a random value so that regular CRL regeneration is
                    # distributed a bit
                    cache_expires = expires - random.randint(1, 5) * 60

                if cache.get(cache_key) is None:
                    if crl is None:
                        crl = self.get_crl(expires=expires, algorithm=algorithm, password=password,
                                           scope=scope, full_name=full_name, relative_name=relative_name)

                    encoded_crl = crl.public_bytes(encoding)
                    cache.set(cache_key, encoded_crl, cache_expires) 
Example #7
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 #8
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,)) 
Example #9
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 #10
Source File: tests_command_init_ca.py    From django-ca with GNU General Public License v3.0 4 votes vote down vote up
def test_arguments(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='DSA',
                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.assertPrivateKey(ca)
        self.assertSerial(ca.serial)
        ca.full_clean()  # assert e.g. max_length in serials
        self.assertSignature([ca], ca)
        self.assertEqual(ca.name_constraints, NameConstraints({'value': {
            'permitted': ['DNS:.com'],
            'excluded': ['DNS:.net']
        }}))

        # test the private key
        key = ca.key(None)
        self.assertIsInstance(key, dsa.DSAPrivateKey)
        self.assertEqual(key.key_size, 1024)

        self.assertTrue(isinstance(ca.x509.signature_hash_algorithm, hashes.SHA1))
        self.assertTrue(isinstance(ca.x509.public_key(), dsa.DSAPublicKey))
        self.assertIsNone(ca.crl_distribution_points)
        self.assertEqual(ca.authority_information_access, AuthorityInformationAccess(
            {'value': {'issuers': ['URI:http://ca.issuer.ca.example.com']}}))
        self.assertEqual(ca.name_constraints, NameConstraints({'value': {
            'permitted': ['DNS:.com'],
            'excluded': ['DNS:.net']
        }}))
        self.assertEqual(ca.pathlen, 3)
        self.assertEqual(ca.max_pathlen, 3)
        self.assertTrue(ca.allows_intermediate_ca)
        self.assertEqual(ca.issuer_url, 'http://issuer.ca.example.com')
        self.assertEqual(ca.issuer_alt_name, 'URI:http://ian.ca.example.com')
        self.assertEqual(ca.crl_url, 'http://crl.example.com')
        self.assertEqual(ca.ocsp_url, 'http://ocsp.example.com')
        self.assertIssuer(ca, ca)
        self.assertAuthorityKeyIdentifier(ca, ca)