当前位置: 首页>>代码示例>>Python>>正文


Python Context.use_privatekey_file方法代码示例

本文整理汇总了Python中OpenSSL.SSL.Context.use_privatekey_file方法的典型用法代码示例。如果您正苦于以下问题:Python Context.use_privatekey_file方法的具体用法?Python Context.use_privatekey_file怎么用?Python Context.use_privatekey_file使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在OpenSSL.SSL.Context的用法示例。


在下文中一共展示了Context.use_privatekey_file方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from OpenSSL.SSL import Context [as 别名]
# 或者: from OpenSSL.SSL.Context import use_privatekey_file [as 别名]
    def __init__(self, HOST='130.236.216.131', PORT = 443):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        context = Context(TLSv1_METHOD)
        context.use_certificate_file((self.certpath))
        context.use_privatekey_file(self.keypath)
        context.set_timeout(2)
        conn = Connection(context,s)
        conn.bind((HOST,PORT))

        print 'Server is listening...'
        conn.listen(5)
        # self.client_table is a dictionary of clients
        # where key = unique id and value = socket
        self.client_table = {} 
        self.id_counter = 0
        self.in_q = Queue.Queue()
        self.out_q = Queue.Queue()
        threading.Thread(target=self.sendinput).start()
        threading.Thread(target=self.in_processor).start()
        threading.Thread(target=self.out_processor).start()
        try:
            while True:
        # Waiting for new client to accept, sslsocket is the socket that will be used for communication with this client after a client sets up a connection with the server
                sslsocket, addr = conn.accept()
                self.client_table[self.id_counter] = sslsocket
                self.id_counter = self.id_counter + 1
                threading.Thread(target=self.client_handler,args=(self.id_counter-1,)).start()
        except KeyboardInterrupt:
            for key, value in self.client_table.iteritems():
                value.shutdown()
                value.close()
            sys.exit(0)
开发者ID:dreamwave,项目名称:rad,代码行数:34,代码来源:socketserver.py

示例2: go

# 需要导入模块: from OpenSSL.SSL import Context [as 别名]
# 或者: from OpenSSL.SSL.Context import use_privatekey_file [as 别名]
def go():
    def cb(a, b, c):
        print count.next()
        return "foobar"
    c = Context(TLSv1_METHOD)
    c.set_passwd_cb(cb)
    while 1:
        c.use_privatekey_file('pkey.pem')
开发者ID:Bluehorn,项目名称:pyopenssl,代码行数:10,代码来源:context-passphrase-callback.py

示例3: __init__

# 需要导入模块: from OpenSSL.SSL import Context [as 别名]
# 或者: from OpenSSL.SSL.Context import use_privatekey_file [as 别名]
 def __init__(self, server_address, HandlerClass, bind_and_activate=True):
     socketserver.TCPServer.__init__(self, server_address, HandlerClass)
     ctx = Context(TLSv1_2_METHOD)
     ctx.use_privatekey_file (settings.ssl_key_path)
     ctx.use_certificate_file(settings.ssl_cert_path)
     # only allow clients with cert:
     ctx.set_verify(VERIFY_PEER | VERIFY_CLIENT_ONCE | VERIFY_FAIL_IF_NO_PEER_CERT, self._accept)
     #ctx.set_verify(VERIFY_PEER | VERIFY_CLIENT_ONCE, self._accept)
     self.socket = Connection(ctx, socket.socket(self.address_family, self.socket_type))
     if bind_and_activate:
         self.server_bind()
         self.server_activate()
开发者ID:h4ck3rm1k3,项目名称:openmedialibrary,代码行数:14,代码来源:server.py

示例4: __call__

# 需要导入模块: from OpenSSL.SSL import Context [as 别名]
# 或者: from OpenSSL.SSL.Context import use_privatekey_file [as 别名]
 def __call__(self,connection):
     try:
         servername = re.sub('^[^.]*\.(?=\w+\.\w+$)','',connection.get_servername())
         key,cert = self.certificates[servername]
     except KeyError as e:
         print e
     except Exception as e:
         print e
     new_context = Context(TLSv1_METHOD)
     new_context.use_privatekey_file(key)
     new_context.use_certificate_file(cert)
     connection.set_context(new_context)
开发者ID:DeaconDesperado,项目名称:twsrv,代码行数:14,代码来源:__init__.py

示例5: getContext

# 需要导入模块: from OpenSSL.SSL import Context [as 别名]
# 或者: from OpenSSL.SSL.Context import use_privatekey_file [as 别名]
    def getContext(self):
        """Create an SSL context.

        This is a sample implementation that loads a certificate from a file
        called 'server.pem'."""
        ctx = SSL_Context(SSLv23_METHOD)
        ctx.use_certificate_file(self.certificateFileName)
        ctx.use_privatekey_file(self.privateKeyFileName)
        ctx.load_client_ca(self.certificateChainFile)
        ctx.load_verify_locations(self.certificateChainFile)
        ctx.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT,
                self._verify)
        ctx.set_verify_depth(10)
        return ctx
开发者ID:maximerobin,项目名称:Ufwi,代码行数:16,代码来源:ssl_strict.py

示例6: cacheContext

# 需要导入模块: from OpenSSL.SSL import Context [as 别名]
# 或者: from OpenSSL.SSL.Context import use_privatekey_file [as 别名]
    def cacheContext(self):
        # Unfortunate code duplication.
        ctx = SSLContext(self.sslmethod)

        if self.ciphers is not None:
            ctx.set_cipher_list(self.ciphers)

        if self.passwdCallback is not None:
            ctx.set_passwd_cb(self.passwdCallback)

        ctx.use_certificate_file(self.certificateFileName)
        ctx.use_privatekey_file(self.privateKeyFileName)

        if self.certificateChainFile != "":
            ctx.use_certificate_chain_file(self.certificateChainFile)

        self._context = ctx
开发者ID:anemitz,项目名称:calendarserver,代码行数:19,代码来源:ssl.py

示例7: getContext

# 需要导入模块: from OpenSSL.SSL import Context [as 别名]
# 或者: from OpenSSL.SSL.Context import use_privatekey_file [as 别名]
  def getContext(self):
    ctx = Context(TLSv1_METHOD)
    store = ctx.get_cert_store()
    data = open("ssl-keys/ca.crt").read()
    x509 = load_certificate(FILETYPE_PEM, data)
    store.add_cert(x509)

    ctx.use_privatekey_file('ssl-keys/server.key.insecure', FILETYPE_PEM)
    ctx.use_certificate_file('ssl-keys/server.crt', FILETYPE_PEM)

    # throws an error if private and public key not match
    ctx.check_privatekey()

    ctx.set_verify(VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, self.verifyHostname)
    ctx.set_options(OP_NO_SSLv3)

    return ctx
开发者ID:amirmc,项目名称:signpost,代码行数:19,代码来源:signpost_auth.py

示例8: getContext

# 需要导入模块: from OpenSSL.SSL import Context [as 别名]
# 或者: from OpenSSL.SSL.Context import use_privatekey_file [as 别名]
    def getContext(self):
        """Creates a context.

        This will make contexts using ``SSLv23_METHOD``. This is
        because OpenSSL thought it would be a good idea to have
        ``TLSv1_METHOD`` mean "only use TLSv1.0" -- specifically, it
        disables TLSv1.2. Since we don't want to use SSLv2 and v3, we
        set OP_NO_SSLv2|OP_NO_SSLv3. Additionally, we set
        OP_SINGLE_DH_USE.

        """
        ctx = Context(SSLv23_METHOD)
        ctx.use_certificate_file("cert.pem")
        ctx.use_privatekey_file("key.pem")
        ctx.load_tmp_dh("dhparam.pem")
        ctx.set_options(OP_SINGLE_DH_USE|OP_NO_SSLv2|OP_NO_SSLv3)
        ctx.set_verify(VERIFY_PEER, self._verify)
        return ctx
开发者ID:BanzaiMan,项目名称:merlyn,代码行数:20,代码来源:auth.py

示例9: cacheContext

# 需要导入模块: from OpenSSL.SSL import Context [as 别名]
# 或者: from OpenSSL.SSL.Context import use_privatekey_file [as 别名]
    def cacheContext(self):
        # Unfortunate code duplication.
        ctx = SSLContext(self.sslmethod)

        # Always disable SSLv2/SSLv3
        ctx.set_options(OP_NO_SSLv2)
        ctx.set_options(OP_NO_SSLv3)

        if self.ciphers is not None:
            ctx.set_cipher_list(self.ciphers)
            ctx.set_options(OP_CIPHER_SERVER_PREFERENCE)

        if self.passwdCallback is not None:
            ctx.set_passwd_cb(self.passwdCallback)

        ctx.use_certificate_file(self.certificateFileName)
        ctx.use_privatekey_file(self.privateKeyFileName)

        if self.certificateChainFile != "":
            ctx.use_certificate_chain_file(self.certificateChainFile)

        self._context = ctx
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:24,代码来源:ssl.py

示例10: test_set_passwd_cb

# 需要导入模块: from OpenSSL.SSL import Context [as 别名]
# 或者: from OpenSSL.SSL.Context import use_privatekey_file [as 别名]
    def test_set_passwd_cb(self):
        """
        L{Context.set_passwd_cb} accepts a callable which will be invoked when
        a private key is loaded from an encrypted PEM.
        """
        key = PKey()
        key.generate_key(TYPE_RSA, 128)
        pemFile = self.mktemp()
        fObj = file(pemFile, 'w')
        passphrase = "foobar"
        fObj.write(dump_privatekey(FILETYPE_PEM, key, "blowfish", passphrase))
        fObj.close()

        calledWith = []
        def passphraseCallback(maxlen, verify, extra):
            calledWith.append((maxlen, verify, extra))
            return passphrase
        context = Context(TLSv1_METHOD)
        context.set_passwd_cb(passphraseCallback)
        context.use_privatekey_file(pemFile)
        self.assertTrue(len(calledWith), 1)
        self.assertTrue(isinstance(calledWith[0][0], int))
        self.assertTrue(isinstance(calledWith[0][1], int))
        self.assertEqual(calledWith[0][2], None)
开发者ID:dreamwave,项目名称:rad,代码行数:26,代码来源:test_ssl.py

示例11: Sockets

# 需要导入模块: from OpenSSL.SSL import Context [as 别名]
# 或者: from OpenSSL.SSL.Context import use_privatekey_file [as 别名]
def Sockets(addresses, **args):
	ssl_private_key = args.get('ssl_private_key', args.get('key_file' ))
	ssl_certificate = args.get('ssl_certificate', args.get('cert_file'))

	ssl = ssl_certificate and ssl_private_key
	if ssl:
		if not SSL:
			raise ImportError('you must install pyOpenSSL to use https')

		ctx = SSLContext(SSLv23_METHOD)
		ctx.use_privatekey_file(ssl_private_key)
		ctx.use_certificate_file(ssl_certificate)

		cert = load_certificate(FILETYPE_PEM, open(ssl_certificate, 'rb').read())
		base_environ = dict(HTTPS='on', SSL_SERVER_M_SERIAL  = cert.get_serial_number(),
		                                SSL_SERVER_M_VERSION = cert.get_version())

		for prefix, dn in [("I", cert.get_issuer()), ("S", cert.get_subject())]:
			dnstr = str(dn)[18:-2]
			wsgikey = 'SSL_SERVER_%s_DN' %prefix
			base_environ[wsgikey] = dnstr
			while dnstr:
				pos = dnstr.rfind('=')
				dnstr, value = dnstr[:pos], dnstr[pos + 1:]
				pos = dnstr.rfind('/')
				dnstr, key = dnstr[:pos], dnstr[pos + 1:]
				if key and value:
					wsgikey = 'SSL_SERVER_%s_DN_%s' % (prefix, key)
					base_environ[wsgikey] = value

		socket_func = lambda family, socktype: \
			SSL(SSLConnection(ctx, Socket(family, socktype)))
		fromfd_func = lambda fileno, family, socktype: \
			SSL(SSLConnection(ctx, fromfd(fileno, family, socktype)))
	else:
		fromfd_func, socket_func, base_environ = fromfd, Socket, {}

	if isinstance(addresses, basestring):
		addresses, addrs = [], [i for i in str(addresses).split(',') if i.strip()]
		for addr in addrs:
			is_ipv6 = R_IPV6(addr)
			if is_ipv6:
				addresses.append((AF_INET6, is_ipv6.groups()))
				continue

			seq = [i.strip() for i in addr.split(':')]
			if len(seq) == 2:
				if seq[0].lower() in ('fromfd', 'fileno'):
					addresses.append((AF_INET, int(seq[1])))
					continue

				addresses.append((AF_INET, seq))
				continue

			if len(seq) == 3 and seq[0].lower() in ('fromfd', 'fileno'):
				family = seq[1].lower()
				if   family in ('inet', 'af_inet', 'ipv4'):
					addresses.append((AF_INET, int(seq[2])))
					continue

				elif family in ('inet6', 'af_inet6', 'ipv6', '6'):
					addresses.append((AF_INET, int(seq[2])))
					continue

				elif family in ('unix', 'af_unix', 's', 'socket',
				           'unix_socket', 'unixsocket', 'unixsock'):

					addresses.append((_socket.AF_UNIX, int(seq[2])))
					continue

			addresses.append((_socket.AF_UNIX, addr.strip()))
	else:
		addresses, addrs = [], addresses
		for addr in addrs:
			if isinstance(addr, (int, long)):
				addresses.append((AF_INET, addr))
				continue

			if isinstance(addr, (list, tuple)) and len(addr) == 2:
				if isinstance(addr[0], (int, long)):
					address.append(addr)
					continue

				if isinstance(addr[0], basestring):
					addresses.append((AF_INET6, addr) if ':' in addr[0] \
					            else (AF_INET , addr))
					continue

			if isinstance(addr, basestring):
				addresses.append((_socket.AF_UNIX, addr))
				continue

			raise ValueError('bad address %r' %addr)

	sockets = []
	for family, addr in addresses:
		if isinstance(addr, (int, long)):
			sock = fromfd_func(addr, family, SOCK_STREAM)
			sock.setblocking(0)

#.........这里部分代码省略.........
开发者ID:ZoomQuiet,项目名称:eurasia,代码行数:103,代码来源:socket2.py


注:本文中的OpenSSL.SSL.Context.use_privatekey_file方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。