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

Python ssl.KeyPair类代码示例

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

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



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

示例1: 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


示例2: 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


示例3: flocker_keypair

def flocker_keypair():
    """
    Create a new 4096-bit RSA key pair.
    """
    return ComparableKeyPair(
        keypair=KeyPair.generate(crypto.TYPE_RSA, size=4096)
    )
开发者ID:gideonmay,项目名称:flocker,代码行数:7,代码来源:_ca.py


示例4: generate_keypair

def generate_keypair():
    """
    Create a new 4096-bit RSA key pair.
    """
    return FlockerKeyPair(
        keypair=KeyPair.generate(crypto.TYPE_RSA, size=4096)
    )
开发者ID:ALSEDLAH,项目名称:flocker,代码行数:7,代码来源:_ca.py


示例5: testBadCertRequestSubject

    def testBadCertRequestSubject(self):
        kp = KeyPair.generate()
        subject = DistinguishedName(commonName='HACKERX',
                                    localityName='INTERNETANIA')
        reqobj = kp.requestObject(subject)

        fakereq = kp.requestObject(subject)
        ssigned = kp.signRequestObject(subject, fakereq, 1)
        certpair = PrivateCertificate.fromCertificateAndKeyPair
        fakecert = certpair(ssigned, kp)
        apc = self.serverService2.certificateStorage.addPrivateCertificate

        def _2(secured):
            D = secured.callRemote(
                q2q.Sign,
                certificate_request=reqobj,
                password='itdoesntmatter')
            def _1(dcert):
                cert = dcert['certificate']
                privcert = certpair(cert, kp)
                apc(str(self.fromAddress), privcert)
            return D.addCallback(_1)

        d = self.serverService2.getSecureConnection(
            self.fromAddress, self.fromAddress.domainAddress(), authorize=False,
            usePrivateCertificate=fakecert,
            ).addCallback(_2)

        def unexpectedSuccess(result):
            self.fail("Expected BadCertificateRequest, got %r" % (result,))
        def expectedFailure(err):
            err.trap(q2q.BadCertificateRequest)
        d.addCallbacks(unexpectedSuccess, expectedFailure)
        return d
开发者ID:exarkun,项目名称:vertex,代码行数:34,代码来源:test_q2q.py


示例6: 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


示例7: 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


示例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: requestCert

def requestCert(config):
    subject = config['subject']
    path = config['path']

    store = yield config.parent.storeDeferred

    key = KeyPair.loadPEM(path.getContent())
    req = generateCertificateRequest(key, subject)
    yield store.submitCertificateRequest(req)
开发者ID:tomprince,项目名称:deed,代码行数:9,代码来源:tool.py


示例10: makeCert

def makeCert(cn):
    """
    Create a self-signed cert.
    """
    sharedDN = DN(CN=cn)
    key = KeyPair.generate()
    cr = key.certificateRequest(sharedDN)
    sscrd = key.signCertificateRequest(sharedDN, cr, lambda dn: True, 1)
    return key.newCertificate(sscrd)
开发者ID:washort,项目名称:vertex,代码行数:9,代码来源:test_identity.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: 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


示例13: new_tahoe_configuration

def new_tahoe_configuration(deploy_config, bucketname, key_prefix, publichost, privatehost, introducer_port, storageserver_port):
    """
    Create brand new secrets and configuration for use by an
    introducer/storage pair.
    """
    base_name = dict(
        organizationName=b"Least Authority Enterprises",
        organizationalUnitName=b"S4",
        emailAddress=bucketname,
    )

    keypair = KeyPair.generate(size=2048)
    introducer_certificate = keypair.selfSignedCert(
        serialNumber=1,
        commonName=b"introducer",
        **base_name
    )
    storage_certificate = keypair.selfSignedCert(
        serialNumber=1,
        commonName=b"storage",
        **base_name
    )
    def pem(key, cert):
        return b"\n".join((key.dump(FILETYPE_PEM), cert.dump(FILETYPE_PEM)))

    introducer_tub = Tub(certData=pem(keypair, introducer_certificate))
    introducer_tub.setLocation("{}:{}".format(publichost, introducer_port))
    storage_tub = Tub(certData=pem(keypair, storage_certificate))

    return marshal_tahoe_configuration(
        introducer_pem=introducer_tub.getCertData().strip(),

        storage_pem=storage_tub.getCertData().strip(),
        storage_privkey=keyutil.make_keypair()[0] + b"\n",

        introducer_port=introducer_port,
        storageserver_port=storageserver_port,

        bucket_name=bucketname,
        key_prefix=key_prefix,
        publichost=publichost,
        privatehost=privatehost,
        # The object of the reference is irrelevant.  The furl will
        # get hooked up to something else when Tahoe really runs.
        # Just need to pass something _weak referenceable_!  Which
        # rules out a lot of things...
        introducer_furl=introducer_tub.registerReference(introducer_tub),

        s3_access_key_id=deploy_config.s3_access_key_id,
        s3_secret_key=deploy_config.s3_secret_key,

        log_gatherer_furl=deploy_config.log_gatherer_furl,
        stats_gatherer_furl=deploy_config.stats_gatherer_furl,
    )
开发者ID:LeastAuthority,项目名称:leastauthority.com,代码行数:54,代码来源:server.py


示例14: makeCertRequest

def makeCertRequest(cn):
    """
    Create a certificate request with the given common name.

    @param cn: Common Name to use in certificate request.
    @type cn: L{bytes}

    @return: Certificate request.
    @rtype: L{CertificateRequest}
    """
    key = KeyPair.generate()
    return key.certificateRequest(DN(CN=cn))
开发者ID:chellygel,项目名称:vertex,代码行数:12,代码来源:test_identity.py


示例15: start_ssl

    def start_ssl(self):
        log.debug("Enabling SSL with PKey: %s, Cert: %s", self.pkey, self.cert)
        check_ssl_keys()

        with open(configmanager.get_config_dir(self.cert)) as cert:
            certificate = Certificate.loadPEM(cert.read()).original
        with open(configmanager.get_config_dir(self.pkey)) as pkey:
            private_key = KeyPair.load(pkey.read(), FILETYPE_PEM).original
        options = CertificateOptions(privateKey=private_key, certificate=certificate, method=SSL.SSLv23_METHOD)
        options.getContext().set_options(SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3)

        self.socket = reactor.listenSSL(self.port, self.site, options)
        log.info("Serving on %s:%s view at https://127.0.0.1:%s", "0.0.0.0", self.port, self.port)
开发者ID:Kash-Krishna,项目名称:SharkByte,代码行数:13,代码来源:server.py


示例16: fromFilePath

    def fromFilePath(cls, filePath):
        privatePath = filePath.child('private')
        publicPath = filePath.child('public')
        csrPath = filePath.child('csr')

        issuerPath = filePath.child('issuer')
        if issuerPath.exists():
            issuer = issuerPath.getContent()
            key = KeyPair.loadPEM(privatePath.child(issuer).getContent())
            cert = Certificate.loadPEM(publicPath.child(issuer).getContent())

        store = cls(publicPath, privatePath, csrPath, key, cert, issuer)
        return store
开发者ID:tomprince,项目名称:deed,代码行数:13,代码来源:authority.py


示例17: _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


示例18: createCertificate

def createCertificate():
    # this is copied from test_sslverify.py
    dn = DistinguishedName(commonName="newpb_thingy")
    keypair = KeyPair.generate(size=2048)
    req = keypair.certificateRequest(dn, digestAlgorithm="sha256")
    certData = keypair.signCertificateRequest(dn, req,
                                              lambda dn: True,
                                              1, # serial number
                                              digestAlgorithm="sha256",
                                              )
    cert = keypair.newCertificate(certData)
    #opts = cert.options()
    # 'opts' can be given to reactor.listenSSL, or to transport.startTLS
    return cert
开发者ID:FiloSottile,项目名称:foolscap,代码行数:14,代码来源:crypto.py


示例19: from_path

    def from_path(cls, path):
        """
        :param FilePath path: Directory where private key and certificate are
            stored.
        """
        if not path.isdir():
            raise PathError(
                b"Path {path} is not a directory.".format(path=path.path)
            )

        certPath = path.child(certificate_filename)
        keyPath = path.child(key_filename)

        if not certPath.isfile():
            raise PathError(
                b"Certificate file {path} does not exist.".format(
                    path=certPath.path)
            )

        if not keyPath.isfile():
            raise PathError(
                b"Private key file {path} does not exist.".format(
                    path=keyPath.path)
            )

        try:
            certFile = certPath.open()
        except IOError:
            raise PathError(
                (b"Certificate file {path} could not be opened. "
                 b"Check file permissions.").format(
                    path=certPath.path)
            )

        try:
            keyFile = keyPath.open()
        except IOError:
            raise PathError(
                (b"Private key file {path} could not be opened. "
                 b"Check file permissions.").format(
                    path=keyPath.path)
            )

        certificate = Certificate.load(
            certFile.read(), format=crypto.FILETYPE_PEM)
        keypair = FlockerKeyPair(
            keypair=KeyPair.load(keyFile.read(), format=crypto.FILETYPE_PEM)
        )

        return cls(path=path, certificate=certificate, keypair=keypair)
开发者ID:ALSEDLAH,项目名称:flocker,代码行数:50,代码来源:_ca.py


示例20: makeCert

def makeCert(cn):
    """
    Create a self-signed certificate with the given common name.

    @param cn: Common Name to use in certificate.
    @type cn: L{bytes}

    @return: Self-signed certificate.
    @rtype: L{Certificate<twisted.internet.ssl.Certificate>}
    """
    sharedDN = DN(CN=cn)
    key = KeyPair.generate()
    cr = key.certificateRequest(sharedDN)
    sscrd = key.signCertificateRequest(sharedDN, cr, lambda dn: True, 1)
    return key.newCertificate(sscrd)
开发者ID:chellygel,项目名称:vertex,代码行数:15,代码来源:test_identity.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python ssl.PrivateCertificate类代码示例发布时间:2022-05-27
下一篇:
Python ssl.ClientContextFactory类代码示例发布时间: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