• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python ssl.PrivateCertificate类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中twisted.internet.ssl.PrivateCertificate的典型用法代码示例。如果您正苦于以下问题:Python PrivateCertificate类的具体用法?Python PrivateCertificate怎么用?Python PrivateCertificate使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: connect

    def connect(self, host=None, port=None, cert=None, key=None):
        '''
        Connect to another portal somewhere. If retry is set, will attempt to reconnect
        with the target continuously. As of the time of this writing, you cannot stop a 
        polling connection without taking down the portal.

        :param retry: continuously attempt to connect on drops or rejections
        :type retry: bool.
        '''

        host = host if host else self.host
        port = port if port else self.port
        cert = cert if cert else self.certCa
        key = key if key else self.keyPrivate  # ???

        # the first term is the name the server is using in the cert (for now)
        ctx = optionsForClientTLS(u"pds.production", Certificate.loadPEM(cert), PrivateCertificate.loadPEM(key))

        factory = RiffleClientFactory()
        SSL4ClientEndpoint(reactor, host, port, ctx,).connect(factory)

        print 'Connecting to ' + host + ':' + str(port)
        avatar = yield factory.login(self)

        defer.returnValue(Levy(avatar))
开发者ID:SejalChauhan,项目名称:Paradrop,代码行数:25,代码来源:riffle.py


示例2: setUp

    def setUp(self):
        """
        Create a L{PantheonHTTPChecker} pointed at a mock authentication service
        with some simple site and user information.
        """
        self.site = 'example.com'
        self.cwd = '/some/path'
        self.uid = 1542
        self.username = 'alice'
        self.password = 'correct password'
        keyString = FilePath(__file__).sibling('id_rsa').getContent()
        self.privateKey = Key.fromString(keyString)

        caKeyString = FilePath(__file__).sibling('cakey.pem').getContent()
        self.caKey = KeyPair.load(caKeyString, FILETYPE_PEM)
        caCertString = FilePath(__file__).sibling('cacert.pem').getContent()
        self.caCert = PrivateCertificate.load(
            caCertString, self.caKey, FILETYPE_PEM)

        self.resource = MockPantheonAuthResource(
            sites={self.site: [self.username]},
            authorizations={self.site: dict(cwd=self.cwd, uid=self.uid)},
            passwords={self.username: self.password},
            keys={self.username: self.privateKey},
            )
        self.server = MockPantheonAuthServer(
            reactor, self.resource, self.caCert)
        self.server.startService()
        self.addCleanup(self.server.stopService)
开发者ID:exarkun,项目名称:Pantheon-SSH,代码行数:29,代码来源:fakebackend.py


示例3: getFactory

    def getFactory(self):
        if self.factory is None:
            if self.certificateFile is not None:
                cert = PrivateCertificate.loadPEM(
                    file(self.certificateFile).read())
                certOpts = CertificateOptions(
                    cert.privateKey.original,
                    cert.original,
                    requireCertificate=False,
                    method=SSL.SSLv23_METHOD)
            else:
                certOpts = None

            self.portal = portal.Portal(
                self.userbase, [self.userbase, checkers.AllowAnonymousAccess()])
            self.factory = ESMTPFactory(
                self.portal,
                self.domain,
                {'CRAM-MD5': credentials.CramMD5Credentials,
                 'LOGIN': imap4.LOGINCredentials,
                 },
                certOpts)
            if self.debug:
                self.factory = policies.TrafficLoggingFactory(self.factory, 'smtp')
        return self.factory
开发者ID:pombredanne,项目名称:quotient,代码行数:25,代码来源:mail.py


示例4: clientCertFor

def clientCertFor(name):
    signingCert = getCAPrivateCert()
    clientKey = KeyPair.generate(size=4096)
    csr = clientKey.requestObject(DN(CN=name), "sha1")
    clientCert = signingCert.signRequestObject(
        csr, serialNumber=1, digestAlgorithm="sha1")
    return PrivateCertificate.fromCertificateAndKeyPair(clientCert, clientKey)
开发者ID:damouse,项目名称:pdservertemp,代码行数:7,代码来源:newcert.py


示例5: clientCertFor

def clientCertFor(p_name):
    l_signingCert = getCAPrivateCert()
    l_clientKey = KeyPair.generate(size = 4096)
    l_csr = l_clientKey.requestObject(DN(CN = p_name), "sha1")
    l_clientCert = l_signingCert.signRequestObject(
        l_csr, serialNumber = 1, digestAlgorithm = "sha1")
    return PrivateCertificate.fromCertificateAndKeyPair(l_clientCert, l_clientKey)
开发者ID:DBrianKimmel,项目名称:PyHouse,代码行数:7,代码来源:newcert.py


示例6: getServerContext

    def getServerContext(self):
        """
        Generate a new L{OpenSSL.SSL.Context} object configured to use a
        certificate signed by C{self.ca} and only accept connections from peers
        which are also using a certificate signed by C{self.ca}.
        """
        # Generate a new key for the server and have the CA sign a certificate
        # for it.
        key = KeyPair.generate(size=512)
        req = key.certificateRequest(DN(commonName='localhost'))
        certData = self.ca.signCertificateRequest(req, lambda dn: True, 1)
        cert = PrivateCertificate.load(certData, key)

        # Use the new key/certificate
        context = Context(TLSv1_METHOD)
        context.use_privatekey(key.original)
        context.use_certificate(cert.original)
        context.check_privatekey()

        # Allow peer certificates signed by the CA
        store = context.get_cert_store()
        store.add_cert(self.ca.original)

        # Verify the peer certificate and require that they have one.
        def verify(conn, cert, errno, depth, preverify_ok):
            return preverify_ok
        context.set_verify(VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify)
        return context
开发者ID:exarkun,项目名称:Pantheon-SSH,代码行数:28,代码来源:fakebackend.py


示例7: private_certificate

    def private_certificate(self):
        """
        Combine private key and certificate into a ``PrivateCertificate``.

        :return: ``PrivateCertificate`` instance.
        """
        return PrivateCertificate.fromCertificateAndKeyPair(
            self.certificate, self.keypair.keypair)
开发者ID:gideonmay,项目名称:flocker,代码行数:8,代码来源:_ca.py


示例8: getServerContext

 def getServerContext(self):
     """
     Return a new SSL context suitable for use in a test server.
     """
     pem = self._pem.getContent()
     cert = PrivateCertificate.load(
         pem, KeyPair.load(pem, FILETYPE_PEM), FILETYPE_PEM)
     return cert.options()
开发者ID:12019,项目名称:OpenWrt_Luci_Lua,代码行数:8,代码来源:test_tls.py


示例9: createCertOptions

def createCertOptions(server):
	pk = None
	cert = None
	if server.cert:
		pc = PrivateCertificate.loadPEM(open(server.cert,"rb").read())
		pk = pc.privateKey.original
		cert = pc.original
	tr = platformTrust() if server.verify else None
	return CertificateOptions(privateKey=pk, certificate=cert, trustRoot=tr)
开发者ID:Clam-,项目名称:pyBurlyBot,代码行数:9,代码来源:settings.py


示例10: main

def main(reactor):
    pemBytes = FilePath(b"ca-private-cert.pem").getContent()
    certificateAuthority = Certificate.loadPEM(pemBytes)
    myCertificate = PrivateCertificate.loadPEM(pemBytes)
    serverEndpoint = SSL4ServerEndpoint(
        reactor, 4321, myCertificate.options(certificateAuthority)
    )
    serverEndpoint.listen(Factory.forProtocol(ReportWhichClient))
    return Deferred()
开发者ID:damouse,项目名称:pdservertemp,代码行数:9,代码来源:whichclient.py


示例11: getCAPrivateCert

def getCAPrivateCert():
    privatePath = FilePath(b"ca-private-cert.pem")
    if privatePath.exists():
        return PrivateCertificate.loadPEM(privatePath.getContent())
    else:
        caKey = KeyPair.generate(size=4096)
        caCert = caKey.selfSignedCert(1, CN="the-authority")
        privatePath.setContent(caCert.dumpPEM())
        return caCert
开发者ID:damouse,项目名称:pdservertemp,代码行数:9,代码来源:newcert.py


示例12: addSubprocesses

 def addSubprocesses(self, fds, name, factory):
     super(HendrixDeploySSL, self).addSubprocesses(fds, name, factory)
     if name == 'main_web_ssl':
         privateCert = PrivateCertificate.loadPEM(
             open(self.options['cert']).read() + open(self.options['key']).read()
         )
         factory = TLSMemoryBIOFactory(
             privateCert.options(), False, factory
         )
开发者ID:SlashRoot,项目名称:hendrix,代码行数:9,代码来源:ssl.py


示例13: getServerContext

 def getServerContext(self):
     """
     Return a new SSL context suitable for use in a test server.
     """
     cert = PrivateCertificate.load(
         self._certificateText,
         KeyPair.load(self._privateKeyText, FILETYPE_PEM),
         FILETYPE_PEM)
     return cert.options()
开发者ID:Almad,项目名称:twisted,代码行数:9,代码来源:test_tls.py


示例14: open

    def open(self, port=None, cert=None):
        '''
        Listen for connections on the given port. 
        '''
        port = port if port else self.port
        cert = cert if cert else self.certCa

        ca = Certificate.loadPEM(cert)
        myCertificate = PrivateCertificate.loadPEM(cert)

        SSL4ServerEndpoint(reactor, port, myCertificate.options(ca)).listen(RiffleServerFactory(self))
开发者ID:SejalChauhan,项目名称:Paradrop,代码行数:11,代码来源:riffle.py


示例15: getContextFactory

 def getContextFactory(self):
     if SSL is None:
         raise RuntimeError("No SSL support: you need to install OpenSSL.")
     cert = PrivateCertificate.loadPEM(
         self.certificatePath.open().read())
     certOpts = CertificateOptions(
         cert.privateKey.original,
         cert.original,
         requireCertificate=False,
         method=SSL.SSLv23_METHOD)
     return certOpts
开发者ID:rcarmo,项目名称:divmod.org,代码行数:11,代码来源:port.py


示例16: start_ssl_cmd_server

def start_ssl_cmd_server():
    with open(settings["Agent_Cert"], 'r') as certfile:
        certdata = certfile.read()
    if settings["Agent_Priv_Key"] != settings["Agent_Cert"]:
        with open(settings.get("Agent_Priv_Key"), 'r') as keyfile:
            certdata += keyfile.read()
    with open(settings.get("Broker_Cert"), 'r') as f:
        authdata = f.read()
    certificate = PrivateCertificate.loadPEM(certdata)
    authority = Certificate.loadPEM(authdata)
    factory = Factory.forProtocol(CommandHandler)
    reactor.listenSSL(int(settings.get("Command_Port")), factory, certificate.options(authority))
开发者ID:caedm,项目名称:cabs,代码行数:12,代码来源:cabsagent.py


示例17: start

    def start(self, fd=None):
        pids = [str(os.getpid())]  # script pid

        if fd is None:
            # anything in this block is only run once

            # TODO add global services here, possibly add a services kwarg on
            # __init__
            self.addGlobalServices()

            self.hendrix.startService()
            if self.options['workers']:
                # Create a new listening port and several other processes to help out.
                childFDs = {0: 0, 1: 1, 2: 2}
                self.fds = {}
                for name in self.servers:
                    port = self.hendrix.get_port(name)
                    fd = port.fileno()
                    childFDs[fd] = fd
                    self.fds[name] = fd

                args = self.getSpawnArgs()
                transports = []
                for i in range(self.options['workers']):
                    transport = reactor.spawnProcess(
                        None, executable, args, childFDs=childFDs, env=environ
                    )
                    transports.append(transport)
                    pids.append(str(transport.pid))
            with open(self.pid, 'w') as pid_file:
                pid_file.write('\n'.join(pids))
        else:
            # Another process created the port, drop the tcp service and
            # just start listening on it.
            fds = pickle.loads(fd)
            factories = {}
            for name in self.servers:
                factory = self.disownService(name)
                factories[name] = factory
            self.hendrix.startService()
            for name, factory in factories.iteritems():
                if name == 'main_web_ssl':
                    privateCert = PrivateCertificate.loadPEM(
                        open(self.options['cert']).read() + open(self.options['key']).read()
                    )
                    factory = TLSMemoryBIOFactory(
                        privateCert.options(), False, factory
                    )
                port = reactor.adoptStreamPort(fds[name], AF_INET, factory)

        reactor.run()
开发者ID:zenweasel,项目名称:hendrix,代码行数:51,代码来源:deploy.py


示例18: _create_tls_client_context

def _create_tls_client_context(config, cbdir, log):
    """
    Create a CertificateOptions object for use with TLS listening endpoints.
    """
    # server hostname: The expected name of the remote host.
    hostname = config['hostname']

    # explicit trust (certificate) root
    ca_certs = None
    if 'ca_certificates' in config:
        log.info("TLS client using explicit trust ({cnt_certs} certificates)", cnt_certs=len(config['ca_certificates']))
        ca_certs = []
        for cert_fname in [os.path.abspath(os.path.join(cbdir, x)) for x in (config['ca_certificates'])]:
            cert = crypto.load_certificate(
                crypto.FILETYPE_PEM,
                six.u(open(cert_fname, 'r').read())
            )
            log.info("TLS client trust root CA certificate loaded from '{fname}'", fname=cert_fname)
            ca_certs.append(cert)
        ca_certs = OpenSSLCertificateAuthorities(ca_certs)
    else:
        log.info("TLS client using platform trust")

    # client key/cert to use
    client_cert = None
    if 'key' in config:
        if 'certificate' not in config:
            raise Exception('TLS client key present, but certificate missing')

        key_fname = os.path.abspath(os.path.join(cbdir, config['key']))
        with open(key_fname, 'r') as f:
            private_key = KeyPair.load(f.read(), format=crypto.FILETYPE_PEM)
            log.info("Loaded client TLS key from '{key_fname}'", key_fname=key_fname)

        cert_fname = os.path.abspath(os.path.join(cbdir, config['certificate']))
        with open(cert_fname, 'r') as f:
            cert = Certificate.loadPEM(f.read(),)
            log.info("Loaded client TLS certificate from '{cert_fname}' (cn='{cert_cn}', sha256={cert_sha256}..)",
                     cert_fname=cert_fname,
                     cert_cn=cert.getSubject().CN,
                     cert_sha256=cert.digest('sha256')[:12])

        client_cert = PrivateCertificate.fromCertificateAndKeyPair(cert, private_key)
    else:
        if 'certificate' in config:
            log.warn('TLS client certificate present, but key is missing')

    # create TLS client context
    ctx = optionsForClientTLS(hostname, trustRoot=ca_certs, clientCertificate=client_cert)

    return ctx
开发者ID:FirefighterBlu3,项目名称:crossbar,代码行数:51,代码来源:endpoint.py


示例19: test_ssl

 def test_ssl(self):
     """
     When passed an SSL strports description, L{clientFromString} returns a
     L{SSL4ClientEndpoint} instance initialized with the values from the
     string.
     """
     reactor = object()
     client = endpoints.clientFromString(
         reactor,
         "ssl:host=example.net:port=4321:privateKey=%s:"
         "certKey=%s:bindAddress=10.0.0.3:timeout=3:caCertsDir=%s" %
          (escapedPEMPathName,
           escapedPEMPathName,
           escapedCAsPathName))
     self.assertIsInstance(client, endpoints.SSL4ClientEndpoint)
     self.assertIdentical(client._reactor, reactor)
     self.assertEqual(client._host, "example.net")
     self.assertEqual(client._port, 4321)
     self.assertEqual(client._timeout, 3)
     self.assertEqual(client._bindAddress, "10.0.0.3")
     certOptions = client._sslContextFactory
     self.assertIsInstance(certOptions, CertificateOptions)
     ctx = certOptions.getContext()
     self.assertIsInstance(ctx, ContextType)
     self.assertEqual(Certificate(certOptions.certificate),
                       testCertificate)
     privateCert = PrivateCertificate(certOptions.certificate)
     privateCert._setPrivateKey(KeyPair(certOptions.privateKey))
     self.assertEqual(privateCert, testPrivateCertificate)
     expectedCerts = [
         Certificate.loadPEM(x.getContent()) for x in
             [casPath.child("thing1.pem"), casPath.child("thing2.pem")]
         if x.basename().lower().endswith('.pem')
     ]
     self.assertEqual(sorted((Certificate(x) for x in certOptions.caCerts),
                             key=lambda cert: cert.digest()),
                      sorted(expectedCerts,
                             key=lambda cert: cert.digest()))
开发者ID:anrysev,项目名称:twisted,代码行数:38,代码来源:test_endpoints.py


示例20: __init__

 def __init__(self, uri, verify, timeout=600, reactor=reactor, clientCert=None):
     Resource.__init__(self)
     self._uri = URLPath.fromString(uri)
     self._verify = verify
     self._timeout = timeout
     self._reactor = reactor
     pool = HTTPConnectionPool(reactor)
     if clientCert is not None:
         clientCert = PrivateCertificate.loadPEM(
             FilePath(clientCert).getContent())
     self._agent = Agent(
         reactor,
         StupidPolicyForHTTPS(InsecureTLSOptions(clientCert)),
         pool=pool)
开发者ID:fusionapp,项目名称:soapproxy,代码行数:14,代码来源:proxy.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python task.coiterate函数代码示例发布时间:2022-05-27
下一篇:
Python ssl.KeyPair类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap