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


Python crypto.load_privatekey方法代码示例

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


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

示例1: from_string

# 需要导入模块: from OpenSSL import crypto [as 别名]
# 或者: from OpenSSL.crypto import load_privatekey [as 别名]
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) 
开发者ID:mortcanty,项目名称:earthengine,代码行数:21,代码来源:crypt.py

示例2: gen_cert

# 需要导入模块: from OpenSSL import crypto [as 别名]
# 或者: from OpenSSL.crypto import load_privatekey [as 别名]
def gen_cert(self, cn, key_size=2048, days=9999):
        logging.debug("Generating cert for " + cn)
        cacert = crypto.load_certificate(crypto.FILETYPE_PEM, self.cert)
        cakey = crypto.load_privatekey(crypto.FILETYPE_PEM, self.key)

        pkey = createKeyPair(crypto.TYPE_RSA, key_size)
        req = createCertRequest(pkey, CN=cn)
        cert = createCertificate(req, (cacert, cakey), 1, (0, 60*60*24*days))

        key_data = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)
        cert_data = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)

        return Cert(key_data, cert_data, self.cert)

#
# Multi-Threaded Generator Plumbing
# 
开发者ID:cea-hpc,项目名称:pcocc,代码行数:19,代码来源:Tbon.py

示例3: test_execute

# 需要导入模块: from OpenSSL import crypto [as 别名]
# 或者: from OpenSSL.crypto import load_privatekey [as 别名]
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) 
开发者ID:google,项目名称:clusterfuzz,代码行数:27,代码来源:oss_fuzz_generate_certs_test.py

示例4: _create_pkcs12_bin

# 需要导入模块: from OpenSSL import crypto [as 别名]
# 或者: from OpenSSL.crypto import load_privatekey [as 别名]
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 
开发者ID:privacyidea,项目名称:privacyidea,代码行数:21,代码来源:certificatetoken.py

示例5: test_set_verify_callback_exception

# 需要导入模块: from OpenSSL import crypto [as 别名]
# 或者: from OpenSSL.crypto import load_privatekey [as 别名]
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)) 
开发者ID:aliyun,项目名称:oss-ftp,代码行数:22,代码来源:test_ssl.py

示例6: test_accept

# 需要导入模块: from OpenSSL import crypto [as 别名]
# 或者: from OpenSSL.crypto import load_privatekey [as 别名]
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()) 
开发者ID:aliyun,项目名称:oss-ftp,代码行数:27,代码来源:test_ssl.py

示例7: test_shutdown_truncated

# 需要导入模块: from OpenSSL import crypto [as 别名]
# 或者: from OpenSSL.crypto import load_privatekey [as 别名]
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) 
开发者ID:aliyun,项目名称:oss-ftp,代码行数:20,代码来源:test_ssl.py

示例8: _client

# 需要导入模块: from OpenSSL import crypto [as 别名]
# 或者: from OpenSSL.crypto import load_privatekey [as 别名]
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 
开发者ID:aliyun,项目名称:oss-ftp,代码行数:20,代码来源:test_ssl.py

示例9: test_key_only

# 需要导入模块: from OpenSSL import crypto [as 别名]
# 或者: from OpenSSL.crypto import load_privatekey [as 别名]
def test_key_only(self):
        """
        A :py:obj:`PKCS12` with only a private key can be exported using
        :py:obj:`PKCS12.export` and loaded again using :py:obj:`load_pkcs12`.
        """
        passwd = b"blah"
        p12 = PKCS12()
        pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
        p12.set_privatekey(pkey)
        self.assertEqual(None, p12.get_certificate())
        self.assertEqual(pkey, p12.get_privatekey())
        try:
            dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
        except Error:
            # Some versions of OpenSSL will throw an exception
            # for this nearly useless PKCS12 we tried to generate:
            # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
            return
        p12 = load_pkcs12(dumped_p12, passwd)
        self.assertEqual(None, p12.get_ca_certificates())
        self.assertEqual(None, p12.get_certificate())

        # OpenSSL fails to bring the key back to us.  So sad.  Perhaps in the
        # future this will be improved.
        self.assertTrue(isinstance(p12.get_privatekey(), (PKey, type(None)))) 
开发者ID:aliyun,项目名称:oss-ftp,代码行数:27,代码来源:test_crypto.py

示例10: gen_pkcs12

# 需要导入模块: from OpenSSL import crypto [as 别名]
# 或者: from OpenSSL.crypto import load_privatekey [as 别名]
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 
开发者ID:aliyun,项目名称:oss-ftp,代码行数:21,代码来源:test_crypto.py

示例11: test_replace

# 需要导入模块: from OpenSSL import crypto [as 别名]
# 或者: from OpenSSL.crypto import load_privatekey [as 别名]
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]) 
开发者ID:aliyun,项目名称:oss-ftp,代码行数:20,代码来源:test_crypto.py

示例12: test_dump_privatekey_passphraseCallback

# 需要导入模块: from OpenSSL import crypto [as 别名]
# 或者: from OpenSSL.crypto import load_privatekey [as 别名]
def test_dump_privatekey_passphraseCallback(self):
        """
        :py:obj:`dump_privatekey` writes an encrypted PEM when given a callback which
        returns the correct passphrase.
        """
        passphrase = b("foo")
        called = []
        def cb(writing):
            called.append(writing)
            return passphrase
        key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
        pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
        self.assertTrue(isinstance(pem, binary_type))
        self.assertEqual(called, [True])
        loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
        self.assertTrue(isinstance(loadedKey, PKeyType))
        self.assertEqual(loadedKey.type(), key.type())
        self.assertEqual(loadedKey.bits(), key.bits()) 
开发者ID:aliyun,项目名称:oss-ftp,代码行数:20,代码来源:test_crypto.py

示例13: __init__

# 需要导入模块: from OpenSSL import crypto [as 别名]
# 或者: from OpenSSL.crypto import load_privatekey [as 别名]
def __init__(self, filename=None, text=None, passphrase=None,
                 filetype="pem", bits=2048, _key=None):
        self.__passphrase = passphrase  # can also be a callable
        if _key is not None:
            key = _key
        else:
            ftype = _FILETYPES[filetype]
            if filename is not None:
                ftype, text = get_type_and_text(filename)
            if text is not None:
                if passphrase is not None:
                    key = crypto.load_privatekey(ftype, text, passphrase)
                else:
                    key = crypto.load_privatekey(ftype, text)
            else:
                key = crypto.PKey()
                key.generate_key(crypto.TYPE_RSA, bits)
        key.check()
        self._key = key 
开发者ID:kdart,项目名称:pycopia,代码行数:21,代码来源:certs.py

示例14: __init__

# 需要导入模块: from OpenSSL import crypto [as 别名]
# 或者: from OpenSSL.crypto import load_privatekey [as 别名]
def __init__(self, cert, key):
        import certifi
        from OpenSSL import crypto
        import urllib3.contrib.pyopenssl

        urllib3.contrib.pyopenssl.inject_into_urllib3()

        pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key)
        x509 = crypto.load_certificate(crypto.FILETYPE_PEM, cert)

        ctx_poolmanager = create_urllib3_context()
        ctx_poolmanager.load_verify_locations(cafile=certifi.where())
        ctx_poolmanager._ctx.use_certificate(x509)
        ctx_poolmanager._ctx.use_privatekey(pkey)
        self._ctx_poolmanager = ctx_poolmanager

        ctx_proxymanager = create_urllib3_context()
        ctx_proxymanager.load_verify_locations(cafile=certifi.where())
        ctx_proxymanager._ctx.use_certificate(x509)
        ctx_proxymanager._ctx.use_privatekey(pkey)
        self._ctx_proxymanager = ctx_proxymanager

        super(_MutualTlsAdapter, self).__init__() 
开发者ID:googleapis,项目名称:google-auth-library-python,代码行数:25,代码来源:requests.py

示例15: AddMachineCertificate

# 需要导入模块: from OpenSSL import crypto [as 别名]
# 或者: from OpenSSL.crypto import load_privatekey [as 别名]
def AddMachineCertificate(self, certificate, private_key):
    """Adds a machine certificate payload to the profile.

    Args:
      certificate: str, PEM-formatted certificate.
      private_key: str, PEM-formatted private key.

    Raises:
      CertificateError: there was an error processing the certificate/key
    """
    try:
      cert = certs.Certificate(certificate)

      pkcs12 = crypto.PKCS12Type()
      pkcs12.set_certificate(crypto.load_certificate(
          crypto.FILETYPE_PEM, certificate))
      pkcs12.set_privatekey(crypto.load_privatekey(
          crypto.FILETYPE_PEM, private_key))
    except (certs.CertError, crypto.Error) as e:
      raise CertificateError(e)

    payload = {PAYLOADKEYS_IDENTIFIER: self._GenerateID('machine_cert'),
               PAYLOADKEYS_TYPE: 'com.apple.security.pkcs12',
               PAYLOADKEYS_DISPLAYNAME: cert.subject_cn,
               'Password': cert.osx_fingerprint}

    try:
      payload[PAYLOADKEYS_CONTENT] = plistlib.Data(
          pkcs12.export(cert.osx_fingerprint))
    except crypto.Error as e:
      raise CertificateError(e)

    # Validate payload to generate its UUID
    ValidatePayload(payload)
    self._auth_cert = payload.get(PAYLOADKEYS_UUID)
    self.AddPayload(payload) 
开发者ID:google,项目名称:macops,代码行数:38,代码来源:profiles.py


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