Python OpenSSL.crypto.FILETYPE_PEM Examples
The following are 30
code examples of OpenSSL.crypto.FILETYPE_PEM().
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: test_ssl.py From oss-ftp with MIT License | 6 votes |
def test_mutated_ca_list(self): """ If the list passed to :py:obj:`Context.set_client_ca_list` is mutated afterwards, this does not affect the list of CA names sent to the client. """ 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 mutated_ca(ctx): L = [cadesc] ctx.set_client_ca_list([cadesc]) L.append(sedesc) return [cadesc] self._check_client_ca_list(mutated_ca)
Example #2
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 #3
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 #4
Source File: test_crypto.py From oss-ftp with MIT License | 6 votes |
def test_extension_count(self): """ :py:obj:`X509.get_extension_count` returns the number of extensions that are present in the certificate. """ pkey = load_privatekey(FILETYPE_PEM, client_key_pem) ca = X509Extension(b('basicConstraints'), True, b('CA:FALSE')) key = X509Extension(b('keyUsage'), True, b('digitalSignature')) subjectAltName = X509Extension( b('subjectAltName'), True, b('DNS:example.com')) # Try a certificate with no extensions at all. c = self._extcert(pkey, []) self.assertEqual(c.get_extension_count(), 0) # And a certificate with one c = self._extcert(pkey, [ca]) self.assertEqual(c.get_extension_count(), 1) # And a certificate with several c = self._extcert(pkey, [ca, key, subjectAltName]) self.assertEqual(c.get_extension_count(), 3)
Example #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
Source File: test_crypto.py From oss-ftp with MIT License | 6 votes |
def test_dump_certificate(self): """ :py:obj:`dump_certificate` writes PEM, DER, and text. """ pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM cert = load_certificate(FILETYPE_PEM, pemData) dumped_pem = dump_certificate(FILETYPE_PEM, cert) self.assertEqual(dumped_pem, cleartextCertificatePEM) dumped_der = dump_certificate(FILETYPE_ASN1, cert) good_der = _runopenssl(dumped_pem, b"x509", b"-outform", b"DER") self.assertEqual(dumped_der, good_der) cert2 = load_certificate(FILETYPE_ASN1, dumped_der) dumped_pem2 = dump_certificate(FILETYPE_PEM, cert2) self.assertEqual(dumped_pem2, cleartextCertificatePEM) dumped_text = dump_certificate(FILETYPE_TEXT, cert) good_text = _runopenssl(dumped_pem, b"x509", b"-noout", b"-text") self.assertEqual(dumped_text, good_text)
Example #16
Source File: localca.py From privacyidea with GNU Affero General Public License v3.0 | 6 votes |
def _get_crl_next_update(filename): """ Read the CRL file and return the next update as datetime :param filename: :return: """ dt = None f = open(filename) crl_buff = f.read() f.close() crl_obj = crypto.load_crl(crypto.FILETYPE_PEM, crl_buff) # Get "Next Update" of CRL # Unfortunately pyOpenSSL does not support this. so we dump the # CRL and parse the text :-/ # We do not want to add dependency to pyasn1 crl_text = to_unicode(crypto.dump_crl(crypto.FILETYPE_TEXT, crl_obj)) for line in crl_text.split("\n"): if "Next Update: " in line: key, value = line.split(":", 1) date = value.strip() dt = datetime.datetime.strptime(date, "%b %d %X %Y %Z") break return dt
Example #17
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 #18
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_dump_privatekey_wrong_args(self): """ :py:obj:`dump_privatekey` raises :py:obj:`TypeError` if called with the wrong number of arguments. """ self.assertRaises(TypeError, dump_privatekey) # If cipher name is given, password is required. self.assertRaises( TypeError, dump_privatekey, FILETYPE_PEM, PKey(), GOOD_CIPHER)
Example #19
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_subject_name_hash(self): """ :py:obj:`X509.subject_name_hash` returns the hash of the certificate's subject name. """ cert = load_certificate(FILETYPE_PEM, self.pemData) self.assertIn( cert.subject_name_hash(), [3350047874, # OpenSSL 0.9.8, MD5 3278919224, # OpenSSL 1.0.0, SHA1 ])
Example #20
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_load_privatekey_passphraseCallback(self): """ :py:obj:`load_privatekey` can create a :py:obj:`PKey` object from an encrypted PEM string if given a passphrase callback which returns the correct password. """ called = [] def cb(writing): called.append(writing) return encryptedPrivateKeyPEMPassphrase key = load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb) self.assertTrue(isinstance(key, PKeyType)) self.assertEqual(called, [False])
Example #21
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_get_subject(self): """ :py:obj:`X509.get_subject` returns an :py:obj:`X509Name` instance. """ cert = load_certificate(FILETYPE_PEM, self.pemData) subj = cert.get_subject() self.assertTrue(isinstance(subj, X509Name)) self.assertEquals( subj.get_components(), [(b('C'), b('US')), (b('ST'), b('IL')), (b('L'), b('Chicago')), (b('O'), b('Testing')), (b('CN'), b('Testing Root CA'))])
Example #22
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_dump_privatekey_unknown_cipher(self): """ :py:obj:`dump_privatekey` raises :py:obj:`ValueError` if called with an unrecognized cipher name. """ key = PKey() key.generate_key(TYPE_RSA, 512) self.assertRaises( ValueError, dump_privatekey, FILETYPE_PEM, key, BAD_CIPHER, "passphrase")
Example #23
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_add_cert_rejects_duplicate(self): """ :py:obj:`X509Store.add_cert` raises :py:obj:`OpenSSL.crypto.Error` if an attempt is made to add the same certificate to the store more than once. """ cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM) store = X509Store() store.add_cert(cert) self.assertRaises(Error, store.add_cert, cert)
Example #24
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_get_extension(self): """ :py:obj:`X509.get_extension` takes an integer and returns an :py:obj:`X509Extension` corresponding to the extension at that index. """ pkey = load_privatekey(FILETYPE_PEM, client_key_pem) ca = X509Extension(b('basicConstraints'), True, b('CA:FALSE')) key = X509Extension(b('keyUsage'), True, b('digitalSignature')) subjectAltName = X509Extension( b('subjectAltName'), False, b('DNS:example.com')) cert = self._extcert(pkey, [ca, key, subjectAltName]) ext = cert.get_extension(0) self.assertTrue(isinstance(ext, X509Extension)) self.assertTrue(ext.get_critical()) self.assertEqual(ext.get_short_name(), b('basicConstraints')) ext = cert.get_extension(1) self.assertTrue(isinstance(ext, X509Extension)) self.assertTrue(ext.get_critical()) self.assertEqual(ext.get_short_name(), b('keyUsage')) ext = cert.get_extension(2) self.assertTrue(isinstance(ext, X509Extension)) self.assertFalse(ext.get_critical()) self.assertEqual(ext.get_short_name(), b('subjectAltName')) self.assertRaises(IndexError, cert.get_extension, -1) self.assertRaises(IndexError, cert.get_extension, 4) self.assertRaises(TypeError, cert.get_extension, "hello")
Example #25
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def _extcert(self, pkey, extensions): cert = X509() cert.set_pubkey(pkey) cert.get_subject().commonName = "Unit Tests" cert.get_issuer().commonName = "Unit Tests" when = b(datetime.now().strftime("%Y%m%d%H%M%SZ")) cert.set_notBefore(when) cert.set_notAfter(when) cert.add_extensions(extensions) return load_certificate( FILETYPE_PEM, dump_certificate(FILETYPE_PEM, cert))
Example #26
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_gmtime_adj_notBefore(self): """ :py:obj:`X509Type.gmtime_adj_notBefore` changes the not-before timestamp to be the current time plus the number of seconds passed in. """ cert = load_certificate(FILETYPE_PEM, self.pemData) now = datetime.utcnow() + timedelta(seconds=100) cert.gmtime_adj_notBefore(100) self.assertEqual(cert.get_notBefore(), b(now.strftime("%Y%m%d%H%M%SZ")))
Example #27
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_get_notAfter(self): """ :py:obj:`X509Type.get_notAfter` returns a string in the format of an ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME internally. """ cert = load_certificate(FILETYPE_PEM, self.pemData) self.assertEqual(cert.get_notAfter(), b("20170611123658Z"))
Example #28
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_get_notBefore(self): """ :py:obj:`X509Type.get_notBefore` returns a string in the format of an ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME internally. """ cert = load_certificate(FILETYPE_PEM, self.pemData) self.assertEqual(cert.get_notBefore(), b("20090325123658Z"))
Example #29
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_verify_success(self): """ :py:obj:`X509Req.verify` returns :py:obj:`True` if called with a :py:obj:`OpenSSL.crypto.PKey` which represents the public part of the key which signed the request. """ request = X509Req() pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM) request.sign(pkey, GOOD_DIGEST) self.assertEqual(True, request.verify(pkey))
Example #30
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_verify_wrong_key(self): """ :py:obj:`X509Req.verify` raises :py:obj:`OpenSSL.crypto.Error` if called with a :py:obj:`OpenSSL.crypto.PKey` which does not represent the public part of the key which signed the request. """ request = X509Req() pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM) request.sign(pkey, GOOD_DIGEST) another_pkey = load_privatekey(FILETYPE_PEM, client_key_pem) self.assertRaises(Error, request.verify, another_pkey)