Python OpenSSL.crypto.Error() Examples

The following are 30 code examples of OpenSSL.crypto.Error(). 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 OpenSSL.crypto , or try the search function .
Example #1
Source File: _openssl_crypt.py    From alfred-gmail with MIT License 6 votes vote down vote up
def from_string(key, password=b'notasecret'):
        """Construct a Signer instance from a string.

        Args:
            key: string, private key in PKCS12 or PEM format.
            password: string, password for the private key file.

        Returns:
            Signer instance.

        Raises:
            OpenSSL.crypto.Error if the key can't be parsed.
        """
        key = _helpers._to_bytes(key)
        parsed_pem_key = _helpers._parse_pem_key(key)
        if parsed_pem_key:
            pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, parsed_pem_key)
        else:
            password = _helpers._to_bytes(password, encoding='utf-8')
            pkey = crypto.load_pkcs12(key, password).get_privatekey()
        return OpenSSLSigner(pkey) 
Example #2
Source File: test_crypto.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_sign(self):
        """
        :py:meth:`X509Req.sign` succeeds when passed a private key object and a valid
        digest function.  :py:meth:`X509Req.verify` can be used to check the signature.
        """
        request = self.signable()
        key = PKey()
        key.generate_key(TYPE_RSA, 512)
        request.set_pubkey(key)
        request.sign(key, GOOD_DIGEST)
        # If the type has a verify method, cover that too.
        if getattr(request, 'verify', None) is not None:
            pub = request.get_pubkey()
            self.assertTrue(request.verify(pub))
            # Make another key that won't verify.
            key = PKey()
            key.generate_key(TYPE_RSA, 512)
            self.assertRaises(Error, request.verify, key) 
Example #3
Source File: _openssl_crypt.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def verify(self, message, signature):
        """Verifies a message against a signature.

        Args:
        message: string or bytes, The message to verify. If string, will be
                 encoded to bytes as utf-8.
        signature: string or bytes, The signature on the message. If string,
                   will be encoded to bytes as utf-8.

        Returns:
            True if message was signed by the private key associated with the
            public key that this object was constructed with.
        """
        message = _to_bytes(message, encoding='utf-8')
        signature = _to_bytes(signature, encoding='utf-8')
        try:
            crypto.verify(self._pubkey, signature, message, 'sha256')
            return True
        except crypto.Error:
            return False 
Example #4
Source File: _openssl_crypt.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def from_string(key_pem, is_x509_cert):
        """Construct a Verified instance from a string.

        Args:
            key_pem: string, public key in PEM format.
            is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it
                          is expected to be an RSA key in PEM format.

        Returns:
            Verifier instance.

        Raises:
            OpenSSL.crypto.Error: if the key_pem can't be parsed.
        """
        key_pem = _to_bytes(key_pem)
        if is_x509_cert:
            pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem)
        else:
            pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem)
        return OpenSSLVerifier(pubkey) 
Example #5
Source File: _openssl_crypt.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def verify(self, message, signature):
        """Verifies a message against a signature.

        Args:
        message: string or bytes, The message to verify. If string, will be
                 encoded to bytes as utf-8.
        signature: string or bytes, The signature on the message. If string,
                   will be encoded to bytes as utf-8.

        Returns:
            True if message was signed by the private key associated with the
            public key that this object was constructed with.
        """
        message = _to_bytes(message, encoding='utf-8')
        signature = _to_bytes(signature, encoding='utf-8')
        try:
            crypto.verify(self._pubkey, signature, message, 'sha256')
            return True
        except crypto.Error:
            return False 
Example #6
Source File: repository_controller.py    From vmaas with GNU General Public License v2.0 6 votes vote down vote up
def _check_cert_expiration_date(self, cert_name, cert):
        try:
            loaded_cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
            expire_date = datetime.strptime(loaded_cert.get_notAfter(), "%Y%m%d%H%M%SZ")
            expire_in = expire_date - datetime.now()
            if expire_in.days > 7:
                self.logger.debug('Certificate %s is ok', cert_name)
                CERT_EXPIRATION.labels(cert_name).state('valid')
            elif 7 >= expire_in.days > 0:
                self.logger.warning('Certificate %s will expire in %s', cert_name, expire_in.days)
                CERT_EXPIRATION.labels(cert_name).state('expire_soon')
            else:
                self.logger.warning('Certificate %s expired!', cert_name)
                CERT_EXPIRATION.labels(cert_name).state('expired')
        except crypto.Error:
            if cert_name:
                self.logger.warning('Certificate not provided or incorrect: %s', cert_name)
                CERT_EXPIRATION.labels(cert_name).state('expired')
            else:
                self.logger.warning('Certificate not provided or incorrect')
                CERT_EXPIRATION.labels('None').state('expired') 
Example #7
Source File: test_crypto.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_key_only(self):
        """
        A :py:obj:`PKCS12` with only a private key can be exported using
        :py:obj:`PKCS12.export` and loaded again using :py:obj:`load_pkcs12`.
        """
        passwd = b"blah"
        p12 = PKCS12()
        pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
        p12.set_privatekey(pkey)
        self.assertEqual(None, p12.get_certificate())
        self.assertEqual(pkey, p12.get_privatekey())
        try:
            dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
        except Error:
            # Some versions of OpenSSL will throw an exception
            # for this nearly useless PKCS12 we tried to generate:
            # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
            return
        p12 = load_pkcs12(dumped_p12, passwd)
        self.assertEqual(None, p12.get_ca_certificates())
        self.assertEqual(None, p12.get_certificate())

        # OpenSSL fails to bring the key back to us.  So sad.  Perhaps in the
        # future this will be improved.
        self.assertTrue(isinstance(p12.get_privatekey(), (PKey, type(None)))) 
Example #8
Source File: _openssl_crypt.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def from_string(key, password=b'notasecret'):
        """Construct a Signer instance from a string.

        Args:
            key: string, private key in PKCS12 or PEM format.
            password: string, password for the private key file.

        Returns:
            Signer instance.

        Raises:
            OpenSSL.crypto.Error if the key can't be parsed.
        """
        key = _to_bytes(key)
        parsed_pem_key = _parse_pem_key(key)
        if parsed_pem_key:
            pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, parsed_pem_key)
        else:
            password = _to_bytes(password, encoding='utf-8')
            pkey = crypto.load_pkcs12(key, password).get_privatekey()
        return OpenSSLSigner(pkey) 
Example #9
Source File: _openssl_crypt.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def from_string(key_pem, is_x509_cert):
        """Construct a Verified instance from a string.

        Args:
            key_pem: string, public key in PEM format.
            is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it
                          is expected to be an RSA key in PEM format.

        Returns:
            Verifier instance.

        Raises:
            OpenSSL.crypto.Error: if the key_pem can't be parsed.
        """
        key_pem = _to_bytes(key_pem)
        if is_x509_cert:
            pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem)
        else:
            pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem)
        return OpenSSLVerifier(pubkey) 
Example #10
Source File: test_crypto.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_invalid_extension(self):
        """
        :py:class:`X509Extension` raises something if it is passed a bad extension
        name or value.
        """
        self.assertRaises(
            Error, X509Extension, b('thisIsMadeUp'), False, b('hi'))
        self.assertRaises(
            Error, X509Extension, b('basicConstraints'), False, b('blah blah'))

        # Exercise a weird one (an extension which uses the r2i method).  This
        # exercises the codepath that requires a non-NULL ctx to be passed to
        # X509V3_EXT_nconf.  It can't work now because we provide no
        # configuration database.  It might be made to work in the future.
        self.assertRaises(
            Error, X509Extension, b('proxyCertInfo'), True,
            b('language:id-ppl-anyLanguage,pathlen:1,policy:text:AB')) 
Example #11
Source File: util.py    From oss-ftp with MIT License 6 votes vote down vote up
def tearDown(self):
        """
        Clean up any files or directories created using :py:meth:`TestCase.mktemp`.
        Subclasses must invoke this method if they override it or the
        cleanup will not occur.
        """
        if False and self._temporaryFiles is not None:
            for temp in self._temporaryFiles:
                if os.path.isdir(temp):
                    shutil.rmtree(temp)
                elif os.path.exists(temp):
                    os.unlink(temp)
        try:
            exception_from_error_queue(Error)
        except Error:
            e = sys.exc_info()[1]
            if e.args != ([],):
                self.fail("Left over errors in OpenSSL error queue: " + repr(e)) 
Example #12
Source File: _openssl_crypt.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def verify(self, message, signature):
        """Verifies a message against a signature.

        Args:
        message: string or bytes, The message to verify. If string, will be
                 encoded to bytes as utf-8.
        signature: string or bytes, The signature on the message. If string,
                   will be encoded to bytes as utf-8.

        Returns:
            True if message was signed by the private key associated with the
            public key that this object was constructed with.
        """
        message = _to_bytes(message, encoding='utf-8')
        signature = _to_bytes(signature, encoding='utf-8')
        try:
            crypto.verify(self._pubkey, signature, message, 'sha256')
            return True
        except crypto.Error:
            return False 
Example #13
Source File: ssl_tools.py    From DeepPavlov with Apache License 2.0 6 votes vote down vote up
def verify_signature(amazon_cert: crypto.X509, signature: str, request_body: bytes) -> bool:
    """Verifies Alexa request signature.

    Args:
        amazon_cert: Pycrypto X509 Amazon certificate.
        signature: Base64 decoded Alexa request signature from Signature HTTP header.
        request_body: full HTTPS request body
    Returns:
        result: True if verification was successful, False if not.
    """
    signature = base64.b64decode(signature)

    try:
        crypto.verify(amazon_cert, signature, request_body, 'sha1')
        result = True
    except crypto.Error:
        result = False

    return result 
Example #14
Source File: _openssl_crypt.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def from_string(key_pem, is_x509_cert):
        """Construct a Verified instance from a string.

        Args:
            key_pem: string, public key in PEM format.
            is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it
                          is expected to be an RSA key in PEM format.

        Returns:
            Verifier instance.

        Raises:
            OpenSSL.crypto.Error: if the key_pem can't be parsed.
        """
        key_pem = _to_bytes(key_pem)
        if is_x509_cert:
            pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem)
        else:
            pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem)
        return OpenSSLVerifier(pubkey) 
Example #15
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 6 votes vote down vote up
def test_load_without_mac(self):
        """
        Loading a PKCS12 without a MAC does something other than crash.
        """
        passwd = b"Lake Michigan"
        p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
        dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
        try:
            recovered_p12 = load_pkcs12(dumped_p12, passwd)
            # The person who generated this PCKS12 should be flogged,
            # or better yet we should have a means to determine
            # whether a PCKS12 had a MAC that was verified.
            # Anyway, libopenssl chooses to allow it, so the
            # pyopenssl binding does as well.
            assert isinstance(recovered_p12, PKCS12)
        except Error:
            # Failing here with an exception is preferred as some openssl
            # versions do.
            pass 
Example #16
Source File: _openssl_crypt.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def from_string(key, password=b'notasecret'):
        """Construct a Signer instance from a string.

        Args:
            key: string, private key in PKCS12 or PEM format.
            password: string, password for the private key file.

        Returns:
            Signer instance.

        Raises:
            OpenSSL.crypto.Error if the key can't be parsed.
        """
        key = _to_bytes(key)
        parsed_pem_key = _parse_pem_key(key)
        if parsed_pem_key:
            pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, parsed_pem_key)
        else:
            password = _to_bytes(password, encoding='utf-8')
            pkey = crypto.load_pkcs12(key, password).get_privatekey()
        return OpenSSLSigner(pkey) 
Example #17
Source File: _openssl_crypt.py    From alfred-gmail with MIT License 6 votes vote down vote up
def from_string(key_pem, is_x509_cert):
        """Construct a Verified instance from a string.

        Args:
            key_pem: string, public key in PEM format.
            is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it
                          is expected to be an RSA key in PEM format.

        Returns:
            Verifier instance.

        Raises:
            OpenSSL.crypto.Error: if the key_pem can't be parsed.
        """
        key_pem = _helpers._to_bytes(key_pem)
        if is_x509_cert:
            pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem)
        else:
            pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem)
        return OpenSSLVerifier(pubkey) 
Example #18
Source File: test_crypto.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_load_without_mac(self):
        """
        Loading a PKCS12 without a MAC does something other than crash.
        """
        passwd = b"Lake Michigan"
        p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
        dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
        try:
            recovered_p12 = load_pkcs12(dumped_p12, passwd)
            # The person who generated this PCKS12 should be flogged,
            # or better yet we should have a means to determine
            # whether a PCKS12 had a MAC that was verified.
            # Anyway, libopenssl chooses to allow it, so the
            # pyopenssl binding does as well.
            self.assertTrue(isinstance(recovered_p12, PKCS12))
        except Error:
            # Failing here with an exception is preferred as some openssl
            # versions do.
            pass 
Example #19
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 6 votes vote down vote up
def test_key_only(self):
        """
        A `PKCS12` with only a private key can be exported using
        `PKCS12.export` and loaded again using `load_pkcs12`.
        """
        passwd = b"blah"
        p12 = PKCS12()
        pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
        p12.set_privatekey(pkey)
        assert None is p12.get_certificate()
        assert pkey == p12.get_privatekey()
        try:
            dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
        except Error:
            # Some versions of OpenSSL will throw an exception
            # for this nearly useless PKCS12 we tried to generate:
            # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
            return
        p12 = load_pkcs12(dumped_p12, passwd)
        assert None is p12.get_ca_certificates()
        assert None is p12.get_certificate()

        # OpenSSL fails to bring the key back to us.  So sad.  Perhaps in the
        # future this will be improved.
        assert isinstance(p12.get_privatekey(), (PKey, type(None))) 
Example #20
Source File: _openssl_crypt.py    From alfred-gmail with MIT License 6 votes vote down vote up
def verify(self, message, signature):
        """Verifies a message against a signature.

        Args:
        message: string or bytes, The message to verify. If string, will be
                 encoded to bytes as utf-8.
        signature: string or bytes, The signature on the message. If string,
                   will be encoded to bytes as utf-8.

        Returns:
            True if message was signed by the private key associated with the
            public key that this object was constructed with.
        """
        message = _helpers._to_bytes(message, encoding='utf-8')
        signature = _helpers._to_bytes(signature, encoding='utf-8')
        try:
            crypto.verify(self._pubkey, signature, message, 'sha256')
            return True
        except crypto.Error:
            return False 
Example #21
Source File: _openssl_crypt.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def verify(self, message, signature):
        """Verifies a message against a signature.

        Args:
        message: string or bytes, The message to verify. If string, will be
                 encoded to bytes as utf-8.
        signature: string or bytes, The signature on the message. If string,
                   will be encoded to bytes as utf-8.

        Returns:
            True if message was signed by the private key associated with the
            public key that this object was constructed with.
        """
        message = _to_bytes(message, encoding='utf-8')
        signature = _to_bytes(signature, encoding='utf-8')
        try:
            crypto.verify(self._pubkey, signature, message, 'sha256')
            return True
        except crypto.Error:
            return False 
Example #22
Source File: _openssl_crypt.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def from_string(key_pem, is_x509_cert):
        """Construct a Verified instance from a string.

        Args:
            key_pem: string, public key in PEM format.
            is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it
                          is expected to be an RSA key in PEM format.

        Returns:
            Verifier instance.

        Raises:
            OpenSSL.crypto.Error: if the key_pem can't be parsed.
        """
        key_pem = _to_bytes(key_pem)
        if is_x509_cert:
            pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem)
        else:
            pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem)
        return OpenSSLVerifier(pubkey) 
Example #23
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 6 votes vote down vote up
def test_sign(self):
        """
        `X509Req.sign` succeeds when passed a private key object and a
        valid digest function. `X509Req.verify` can be used to check
        the signature.
        """
        request = self.signable()
        key = PKey()
        key.generate_key(TYPE_RSA, 512)
        request.set_pubkey(key)
        request.sign(key, GOOD_DIGEST)
        # If the type has a verify method, cover that too.
        if getattr(request, 'verify', None) is not None:
            pub = request.get_pubkey()
            assert request.verify(pub)
            # Make another key that won't verify.
            key = PKey()
            key.generate_key(TYPE_RSA, 512)
            with pytest.raises(Error):
                request.verify(key) 
Example #24
Source File: _openssl_crypt.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def verify(self, message, signature):
        """Verifies a message against a signature.

        Args:
        message: string or bytes, The message to verify. If string, will be
                 encoded to bytes as utf-8.
        signature: string or bytes, The signature on the message. If string,
                   will be encoded to bytes as utf-8.

        Returns:
            True if message was signed by the private key associated with the
            public key that this object was constructed with.
        """
        message = _to_bytes(message, encoding='utf-8')
        signature = _to_bytes(signature, encoding='utf-8')
        try:
            crypto.verify(self._pubkey, signature, message, 'sha256')
            return True
        except crypto.Error:
            return False 
Example #25
Source File: _openssl_crypt.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def from_string(key_pem, is_x509_cert):
        """Construct a Verified instance from a string.

        Args:
            key_pem: string, public key in PEM format.
            is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it
                          is expected to be an RSA key in PEM format.

        Returns:
            Verifier instance.

        Raises:
            OpenSSL.crypto.Error: if the key_pem can't be parsed.
        """
        key_pem = _to_bytes(key_pem)
        if is_x509_cert:
            pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem)
        else:
            pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem)
        return OpenSSLVerifier(pubkey) 
Example #26
Source File: _openssl_crypt.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def from_string(key, password=b'notasecret'):
        """Construct a Signer instance from a string.

        Args:
            key: string, private key in PKCS12 or PEM format.
            password: string, password for the private key file.

        Returns:
            Signer instance.

        Raises:
            OpenSSL.crypto.Error if the key can't be parsed.
        """
        key = _to_bytes(key)
        parsed_pem_key = _parse_pem_key(key)
        if parsed_pem_key:
            pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, parsed_pem_key)
        else:
            password = _to_bytes(password, encoding='utf-8')
            pkey = crypto.load_pkcs12(key, password).get_privatekey()
        return OpenSSLSigner(pkey) 
Example #27
Source File: _openssl_crypt.py    From aqua-monitor with GNU Lesser General Public License v3.0 6 votes vote down vote up
def verify(self, message, signature):
        """Verifies a message against a signature.

        Args:
        message: string or bytes, The message to verify. If string, will be
                 encoded to bytes as utf-8.
        signature: string or bytes, The signature on the message. If string,
                   will be encoded to bytes as utf-8.

        Returns:
            True if message was signed by the private key associated with the
            public key that this object was constructed with.
        """
        message = _to_bytes(message, encoding='utf-8')
        signature = _to_bytes(signature, encoding='utf-8')
        try:
            crypto.verify(self._pubkey, signature, message, 'sha256')
            return True
        except crypto.Error:
            return False 
Example #28
Source File: _openssl_crypt.py    From aqua-monitor with GNU Lesser General Public License v3.0 6 votes vote down vote up
def from_string(key_pem, is_x509_cert):
        """Construct a Verified instance from a string.

        Args:
            key_pem: string, public key in PEM format.
            is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it
                          is expected to be an RSA key in PEM format.

        Returns:
            Verifier instance.

        Raises:
            OpenSSL.crypto.Error: if the key_pem can't be parsed.
        """
        key_pem = _to_bytes(key_pem)
        if is_x509_cert:
            pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem)
        else:
            pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem)
        return OpenSSLVerifier(pubkey) 
Example #29
Source File: _openssl_crypt.py    From aqua-monitor with GNU Lesser General Public License v3.0 6 votes vote down vote up
def from_string(key, password=b'notasecret'):
        """Construct a Signer instance from a string.

        Args:
            key: string, private key in PKCS12 or PEM format.
            password: string, password for the private key file.

        Returns:
            Signer instance.

        Raises:
            OpenSSL.crypto.Error if the key can't be parsed.
        """
        key = _to_bytes(key)
        parsed_pem_key = _parse_pem_key(key)
        if parsed_pem_key:
            pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, parsed_pem_key)
        else:
            password = _to_bytes(password, encoding='utf-8')
            pkey = crypto.load_pkcs12(key, password).get_privatekey()
        return OpenSSLSigner(pkey) 
Example #30
Source File: utils.py    From searchlight with Apache License 2.0 6 votes vote down vote up
def setup_remote_pydev_debug(host, port):
    error_msg = ('Error setting up the debug environment. Verify that the'
                 ' option pydev_worker_debug_host is pointing to a valid '
                 'hostname or IP on which a pydev server is listening on'
                 ' the port indicated by pydev_worker_debug_port.')

    try:
        try:
            from pydev import pydevd
        except ImportError:
            import pydevd

        pydevd.settrace(host,
                        port=port,
                        stdoutToServer=True,
                        stderrToServer=True)
        return True
    except Exception:
        with excutils.save_and_reraise_exception():
            LOG.exception(error_msg)