Python OpenSSL.crypto.load_certificate() Examples
The following are 30
code examples of OpenSSL.crypto.load_certificate().
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: util.py From TabPy with MIT License | 8 votes |
def validate_cert(cert_file_path): with open(cert_file_path, "r") as f: cert_buf = f.read() cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_buf) date_format, encoding = "%Y%m%d%H%M%SZ", "ascii" not_before = datetime.strptime(cert.get_notBefore().decode(encoding), date_format) not_after = datetime.strptime(cert.get_notAfter().decode(encoding), date_format) now = datetime.now() https_error = "Error using HTTPS: " if now < not_before: msg = https_error + f"The certificate provided is not valid until {not_before}." logger.critical(msg) raise RuntimeError(msg) if now > not_after: msg = https_error + f"The certificate provided expired on {not_after}." logger.critical(msg) raise RuntimeError(msg)
Example #2
Source File: certificate_checker.py From IDontSpeakSSL with GNU General Public License v3.0 | 7 votes |
def extract_domains_from_cert(cls, target, certificate_pem, report_folder): domains = [] certificate = crypto.load_certificate(crypto.FILETYPE_PEM, certificate_pem) ext_count = certificate.get_extension_count() for i in range(0,ext_count): try: extension = certificate.get_extension(i).__str__() # might be subject to error if pyopenssl change the representation of data # if it happens, use the extension,get_data() instead if(extension.startswith("DNS:")): for domain in extension.split(' '): domains.append(domain[4:]) except: pass for subject_component in certificate.get_subject().get_components(): if(b'CN' in subject_component): for CN_component in subject_component: if(not CN_component == b'CN'): domains.append(CN_component.decode('utf8')) if(domains): with open('{}/certificates_domains.txt'.format(report_folder), 'a') as domains_file: url = target.replace('_',':') domains_file.write("{}: {}".format(url, ", ".join(domains)))
Example #3
Source File: test_ssl.py From oss-ftp with MIT License | 6 votes |
def _client(self, sock): """ Create a new client-side SSL :py:obj:`Connection` object wrapped around :py:obj:`sock`. """ # Now create the client side Connection. Similar boilerplate to the # above. client_ctx = Context(TLSv1_METHOD) client_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE ) client_ctx.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT|VERIFY_CLIENT_ONCE, verify_cb) client_store = client_ctx.get_cert_store() client_ctx.use_privatekey(load_privatekey(FILETYPE_PEM, client_key_pem)) client_ctx.use_certificate(load_certificate(FILETYPE_PEM, client_cert_pem)) client_ctx.check_privatekey() client_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem)) client_conn = Connection(client_ctx, sock) client_conn.set_connect_state() return client_conn
Example #4
Source File: test_crypto.py From oss-ftp with MIT License | 6 votes |
def test_replace(self): """ :py:obj:`PKCS12.set_certificate` replaces the certificate in a PKCS12 cluster. :py:obj:`PKCS12.set_privatekey` replaces the private key. :py:obj:`PKCS12.set_ca_certificates` replaces the CA certificates. """ p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem) p12.set_certificate(load_certificate(FILETYPE_PEM, server_cert_pem)) p12.set_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem)) root_cert = load_certificate(FILETYPE_PEM, root_cert_pem) client_cert = load_certificate(FILETYPE_PEM, client_cert_pem) p12.set_ca_certificates([root_cert]) # not a tuple self.assertEqual(1, len(p12.get_ca_certificates())) self.assertEqual(root_cert, p12.get_ca_certificates()[0]) p12.set_ca_certificates([client_cert, root_cert]) self.assertEqual(2, len(p12.get_ca_certificates())) self.assertEqual(client_cert, p12.get_ca_certificates()[0]) self.assertEqual(root_cert, p12.get_ca_certificates()[1])
Example #5
Source File: oss_fuzz_generate_certs_test.py From clusterfuzz with Apache License 2.0 | 6 votes |
def test_execute(self): """Tests executing of cron job.""" # Defer import to avoid issues on Python 2. from OpenSSL import crypto self.app.get('/generate-certs') # New cert. tls_cert = ndb.Key(data_types.WorkerTlsCert, 'project1').get() cert = crypto.load_certificate(crypto.FILETYPE_PEM, tls_cert.cert_contents) self.assertEqual('US', cert.get_subject().C) self.assertEqual('*.c.test-clusterfuzz.internal', cert.get_subject().CN) self.assertEqual('project1', cert.get_subject().O) self.assertEqual(9001, cert.get_serial_number()) self.assertEqual(b'20000101000000Z', cert.get_notBefore()) self.assertEqual(b'21000101000000Z', cert.get_notAfter()) private_key = crypto.load_privatekey(crypto.FILETYPE_PEM, tls_cert.key_contents) self.assertTrue(private_key.check()) # Should be unchanged. tls_cert = ndb.Key(data_types.WorkerTlsCert, 'project2').get() self.assertEqual(b'cert_contents', tls_cert.cert_contents) self.assertEqual(b'key_contents', tls_cert.key_contents)
Example #6
Source File: crypt.py From splunk-ref-pas-code with Apache License 2.0 | 6 votes |
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. """ 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 #7
Source File: certificate_generator.py From platform with GNU General Public License v3.0 | 6 votes |
def is_real_certificate_installed(self): if not os.path.exists(self.platform_config.get_ssl_certificate_file()): return False cert = crypto.load_certificate( crypto.FILETYPE_PEM, open(self.platform_config.get_ssl_certificate_file()).read()) if cert.get_issuer().CN == cert.get_subject().CN: self.log.info('issuer: {0}'.format(cert.get_issuer().CN)) self.log.info('self signed certificate') return False if 'Fake' in cert.get_issuer().CN: self.log.info('issuer: {0}'.format(cert.get_issuer().CN)) self.log.info('test certificate') return False self.log.info('real certificate') self.log.info('issuer: {0}, subject: {1}'.format(cert.get_issuer().CN, cert.get_subject().CN)) return True
Example #8
Source File: crypt.py From earthengine with MIT License | 6 votes |
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. """ 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 #9
Source File: crypt.py From sndlatr with Apache License 2.0 | 6 votes |
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. """ 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: certificatetoken.py From privacyidea with GNU Affero General Public License v3.0 | 6 votes |
def _create_pkcs12_bin(self): """ Helper function to create an encrypted pkcs12 binary for download :return: PKCS12 binary """ certificate = self.get_tokeninfo("certificate") privatekey = self.get_tokeninfo("privatekey") pkcs12 = crypto.PKCS12() pkcs12.set_certificate(crypto.load_certificate( crypto.FILETYPE_PEM, certificate)) pkcs12.set_privatekey(crypto.load_privatekey(crypto.FILETYPE_PEM, privatekey)) # TODO define a random passphrase and hand it to the user passphrase = self.token.get_pin() if passphrase == -1: passphrase = "" pkcs12_bin = pkcs12.export(passphrase=passphrase) return pkcs12_bin
Example #11
Source File: test_crypto.py From oss-ftp with MIT License | 6 votes |
def gen_pkcs12(self, cert_pem=None, key_pem=None, ca_pem=None, friendly_name=None): """ Generate a PKCS12 object with components from PEM. Verify that the set functions return None. """ p12 = PKCS12() if cert_pem: ret = p12.set_certificate(load_certificate(FILETYPE_PEM, cert_pem)) self.assertEqual(ret, None) if key_pem: ret = p12.set_privatekey(load_privatekey(FILETYPE_PEM, key_pem)) self.assertEqual(ret, None) if ca_pem: ret = p12.set_ca_certificates((load_certificate(FILETYPE_PEM, ca_pem),)) self.assertEqual(ret, None) if friendly_name: ret = p12.set_friendlyname(friendly_name) self.assertEqual(ret, None) return p12
Example #12
Source File: test_crypto.py From oss-ftp with MIT License | 6 votes |
def test_nullbyte_subjectAltName(self): """ The fields of a `subjectAltName` extension on an X509 may contain NUL bytes and this value is reflected in the string representation of the extension object. """ cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM) ext = cert.get_extension(3) self.assertEqual(ext.get_short_name(), b('subjectAltName')) self.assertEqual( b("DNS:altnull.python.org\x00example.com, " "email:null@python.org\x00user@example.org, " "URI:http://null.python.org\x00http://example.org, " "IP Address:192.0.2.1, IP Address:2001:DB8:0:0:0:0:0:1\n"), b(str(ext)))
Example #13
Source File: test_ssl.py From oss-ftp with MIT License | 6 votes |
def _server(self, sock): """ Create a new server-side SSL :py:obj:`Connection` object wrapped around :py:obj:`sock`. """ # Create the server side Connection. This is mostly setup boilerplate # - use TLSv1, use a particular certificate, etc. server_ctx = Context(TLSv1_METHOD) server_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE ) server_ctx.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT|VERIFY_CLIENT_ONCE, verify_cb) server_store = server_ctx.get_cert_store() server_ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem)) server_ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem)) server_ctx.check_privatekey() server_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem)) # Here the Connection is actually created. If None is passed as the 2nd # parameter, it indicates a memory BIO should be created. server_conn = Connection(server_ctx, sock) server_conn.set_accept_state() return server_conn
Example #14
Source File: test_ssl.py From oss-ftp with MIT License | 6 votes |
def test_shutdown_truncated(self): """ If the underlying connection is truncated, :obj:`Connection.shutdown` raises an :obj:`Error`. """ server_ctx = Context(TLSv1_METHOD) client_ctx = Context(TLSv1_METHOD) server_ctx.use_privatekey( load_privatekey(FILETYPE_PEM, server_key_pem)) server_ctx.use_certificate( load_certificate(FILETYPE_PEM, server_cert_pem)) server = Connection(server_ctx, None) client = Connection(client_ctx, None) self._handshakeInMemory(client, server) self.assertEqual(server.shutdown(), False) self.assertRaises(WantReadError, server.shutdown) server.bio_shutdown() self.assertRaises(Error, server.shutdown)
Example #15
Source File: test_ssl.py From oss-ftp with MIT License | 6 votes |
def test_accept(self): """ :py:obj:`Connection.accept` accepts a pending connection attempt and returns a tuple of a new :py:obj:`Connection` (the accepted client) and the address the connection originated from. """ ctx = Context(TLSv1_METHOD) ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem)) ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem)) port = socket() portSSL = Connection(ctx, port) portSSL.bind(('', 0)) portSSL.listen(3) clientSSL = Connection(Context(TLSv1_METHOD), socket()) # Calling portSSL.getsockname() here to get the server IP address sounds # great, but frequently fails on Windows. clientSSL.connect(('127.0.0.1', portSSL.getsockname()[1])) serverSSL, address = portSSL.accept() self.assertTrue(isinstance(serverSSL, Connection)) self.assertIdentical(serverSSL.get_context(), ctx) self.assertEquals(address, clientSSL.getsockname())
Example #16
Source File: test_ssl.py From oss-ftp with MIT License | 6 votes |
def test_set_multiple_ca_list(self): """ If passed a list containing multiple X509Name objects, :py:obj:`Context.set_client_ca_list` configures the context to send those CA names to the client and, on both the server and client sides, :py:obj:`Connection.get_client_ca_list` returns a list containing those X509Names after the connection is set up. """ secert = load_certificate(FILETYPE_PEM, server_cert_pem) clcert = load_certificate(FILETYPE_PEM, server_cert_pem) sedesc = secert.get_subject() cldesc = clcert.get_subject() def multiple_ca(ctx): L = [sedesc, cldesc] ctx.set_client_ca_list(L) return L self._check_client_ca_list(multiple_ca)
Example #17
Source File: test_ssl.py From oss-ftp with MIT License | 6 votes |
def test_reset_ca_list(self): """ If called multiple times, only the X509Names passed to the final call of :py:obj:`Context.set_client_ca_list` are used to configure the CA names sent to the client. """ cacert = load_certificate(FILETYPE_PEM, root_cert_pem) secert = load_certificate(FILETYPE_PEM, server_cert_pem) clcert = load_certificate(FILETYPE_PEM, server_cert_pem) cadesc = cacert.get_subject() sedesc = secert.get_subject() cldesc = clcert.get_subject() def changed_ca(ctx): ctx.set_client_ca_list([sedesc, cldesc]) ctx.set_client_ca_list([cadesc]) return [cadesc] self._check_client_ca_list(changed_ca)
Example #18
Source File: test_ssl.py From oss-ftp with MIT License | 6 votes |
def test_multiple_add_client_ca(self): """ Multiple CA names can be sent to the client by calling :py:obj:`Context.add_client_ca` with multiple X509 objects. """ cacert = load_certificate(FILETYPE_PEM, root_cert_pem) secert = load_certificate(FILETYPE_PEM, server_cert_pem) cadesc = cacert.get_subject() sedesc = secert.get_subject() def multiple_ca(ctx): ctx.add_client_ca(cacert) ctx.add_client_ca(secert) return [cadesc, sedesc] self._check_client_ca_list(multiple_ca)
Example #19
Source File: test_ssl.py From oss-ftp with MIT License | 6 votes |
def test_set_and_add_client_ca(self): """ A call to :py:obj:`Context.set_client_ca_list` followed by a call to :py:obj:`Context.add_client_ca` results in using the CA names from the first call and the CA name from the second call. """ cacert = load_certificate(FILETYPE_PEM, root_cert_pem) secert = load_certificate(FILETYPE_PEM, server_cert_pem) clcert = load_certificate(FILETYPE_PEM, server_cert_pem) cadesc = cacert.get_subject() sedesc = secert.get_subject() cldesc = clcert.get_subject() def mixed_set_add_ca(ctx): ctx.set_client_ca_list([cadesc, sedesc]) ctx.add_client_ca(clcert) return [cadesc, sedesc, cldesc] self._check_client_ca_list(mixed_set_add_ca)
Example #20
Source File: test_ssl.py From oss-ftp with MIT License | 6 votes |
def test_set_after_add_client_ca(self): """ A call to :py:obj:`Context.set_client_ca_list` after a call to :py:obj:`Context.add_client_ca` replaces the CA name specified by the former call with the names specified by the latter cal. """ cacert = load_certificate(FILETYPE_PEM, root_cert_pem) secert = load_certificate(FILETYPE_PEM, server_cert_pem) clcert = load_certificate(FILETYPE_PEM, server_cert_pem) cadesc = cacert.get_subject() sedesc = secert.get_subject() def set_replaces_add_ca(ctx): ctx.add_client_ca(clcert) ctx.set_client_ca_list([cadesc]) ctx.add_client_ca(secert) return [cadesc, sedesc] self._check_client_ca_list(set_replaces_add_ca)
Example #21
Source File: test_ssl.py From oss-ftp with MIT License | 6 votes |
def test_set_verify_callback_exception(self): """ If the verify callback passed to :py:obj:`Context.set_verify` raises an exception, verification fails and the exception is propagated to the caller of :py:obj:`Connection.do_handshake`. """ serverContext = Context(TLSv1_METHOD) serverContext.use_privatekey( load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)) serverContext.use_certificate( load_certificate(FILETYPE_PEM, cleartextCertificatePEM)) clientContext = Context(TLSv1_METHOD) def verify_callback(*args): raise Exception("silly verify failure") clientContext.set_verify(VERIFY_PEER, verify_callback) exc = self.assertRaises( Exception, self._handshake_test, serverContext, clientContext) self.assertEqual("silly verify failure", str(exc))
Example #22
Source File: crypt.py From billing-export-python with Apache License 2.0 | 6 votes |
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. """ 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_ssl.py From oss-ftp with MIT License | 5 votes |
def test_add_client_ca_errors(self): """ :py:obj:`Context.add_client_ca` raises :py:obj:`TypeError` if called with a non-X509 object or with a number of arguments other than one. """ ctx = Context(TLSv1_METHOD) cacert = load_certificate(FILETYPE_PEM, root_cert_pem) self.assertRaises(TypeError, ctx.add_client_ca) self.assertRaises(TypeError, ctx.add_client_ca, "spam") self.assertRaises(TypeError, ctx.add_client_ca, cacert, cacert)
Example #24
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_load_nul_byte_attribute(self): """ An :py:class:`OpenSSL.crypto.X509Name` from an :py:class:`OpenSSL.crypto.X509` instance loaded from a file can have a NUL byte in the value of one of its attributes. """ cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM) subject = cert.get_subject() self.assertEqual( "null.python.org\x00example.org", subject.commonName)
Example #25
Source File: models.py From django-x509 with BSD 3-Clause "New" or "Revised" License | 5 votes |
def x509(self): """ returns an instance of OpenSSL.crypto.X509 """ if self.certificate: return crypto.load_certificate(crypto.FILETYPE_PEM, self.certificate)
Example #26
Source File: test_ssl.py From oss-ftp with MIT License | 5 votes |
def test_alpn_server_fail(self): """ When clients and servers cannot agree on what protocol to use next the TLS connection does not get established. """ select_args = [] def select(conn, options): select_args.append((conn, options)) return b'' client_context = Context(TLSv1_METHOD) client_context.set_alpn_protos([b'http/1.1', b'spdy/2']) server_context = Context(TLSv1_METHOD) server_context.set_alpn_select_callback(select) # Necessary to actually accept the connection server_context.use_privatekey( load_privatekey(FILETYPE_PEM, server_key_pem)) server_context.use_certificate( load_certificate(FILETYPE_PEM, server_cert_pem)) # Do a little connection to trigger the logic server = Connection(server_context, None) server.set_accept_state() client = Connection(client_context, None) client.set_connect_state() # If the client doesn't return anything, the connection will fail. self.assertRaises(Error, self._interactInMemory, server, client) self.assertEqual([(server, [b'http/1.1', b'spdy/2'])], select_args)
Example #27
Source File: test_ca.py From django-x509 with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_new(self): ca = self._create_ca() self.assertNotEqual(ca.certificate, '') self.assertNotEqual(ca.private_key, '') cert = crypto.load_certificate(crypto.FILETYPE_PEM, ca.certificate) self.assertEqual(int(cert.get_serial_number()), int(ca.serial_number)) subject = cert.get_subject() self.assertEqual(subject.countryName, ca.country_code) self.assertEqual(subject.stateOrProvinceName, ca.state) self.assertEqual(subject.localityName, ca.city) self.assertEqual(subject.organizationName, ca.organization_name) self.assertEqual(subject.emailAddress, ca.email) self.assertEqual(subject.commonName, ca.common_name) issuer = cert.get_issuer() self.assertEqual(issuer.countryName, ca.country_code) self.assertEqual(issuer.stateOrProvinceName, ca.state) self.assertEqual(issuer.localityName, ca.city) self.assertEqual(issuer.organizationName, ca.organization_name) self.assertEqual(issuer.emailAddress, ca.email) self.assertEqual(issuer.commonName, ca.common_name) # ensure version is 3 self.assertEqual(cert.get_version(), 2) # basic constraints e = cert.get_extension(0) self.assertEqual(e.get_critical(), 1) self.assertEqual(e.get_short_name().decode(), 'basicConstraints') self.assertEqual(e.get_data(), b'0\x06\x01\x01\xff\x02\x01\x00')
Example #28
Source File: test_ssl.py From oss-ftp with MIT License | 5 votes |
def test_one_add_client_ca(self): """ A certificate's subject can be added as a CA to be sent to the client with :py:obj:`Context.add_client_ca`. """ cacert = load_certificate(FILETYPE_PEM, root_cert_pem) cadesc = cacert.get_subject() def single_ca(ctx): ctx.add_client_ca(cacert) return [cadesc] self._check_client_ca_list(single_ca)
Example #29
Source File: _sslverify.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def load(Class, requestData, format=crypto.FILETYPE_ASN1, args=()): """ Load a certificate from an ASN.1- or PEM-format string. @rtype: C{Class} """ return Class(crypto.load_certificate(format, requestData), *args) # We can't use super() because it is old style still, so we have to hack # around things wanting to call the parent function
Example #30
Source File: test_ca.py From django-x509 with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_create_old_serial_ca(self): ca = self._create_ca(serial_number=3) self.assertEqual(int(ca.serial_number), 3) cert = crypto.load_certificate(crypto.FILETYPE_PEM, ca.certificate) self.assertEqual(int(cert.get_serial_number()), int(ca.serial_number))