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


Python ssl.PEM_cert_to_DER_cert方法代码示例

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


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

示例1: _extract_x509_certificates

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import PEM_cert_to_DER_cert [as 别名]
def _extract_x509_certificates(x509_certificates):
    keys = []
    for kid, certificate in x509_certificates.iteritems():
        try:
            if certificate.startswith(jwk.PREFIX):
                # The certificate is PEM-encoded
                der = ssl.PEM_cert_to_DER_cert(certificate)
                key = jwk.der2rsa(der)
            else:
                key = jwk.import_rsa_key(certificate)
        except Exception as exception:
            raise UnauthenticatedException(u"Cannot load X.509 certificate",
                                           exception)
        rsa_key = jwk.RSAKey().load_key(key)
        rsa_key.kid = kid
        keys.append(rsa_key)
    return keys 
开发者ID:cloudendpoints,项目名称:endpoints-management-python,代码行数:19,代码来源:suppliers.py

示例2: verify_gtalk_cert

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import PEM_cert_to_DER_cert [as 别名]
def verify_gtalk_cert(self, raw_cert):
        hosts = resolver.get_SRV(self.boundjid.server, 5222,
                                 self.dns_service,
                                 resolver=resolver.default_resolver())
        it_is_google = False
        for host, _ in hosts:
            if host.lower().find('google.com') > -1:
                it_is_google = True

        if it_is_google:
            try:
                if cert.verify('talk.google.com', ssl.PEM_cert_to_DER_cert(raw_cert)):
                    logging.info('google cert found for %s',
                                self.boundjid.server)
                    return
            except cert.CertificateError:
                pass

        logging.error("invalid cert received for %s",
                      self.boundjid.server) 
开发者ID:ustream,项目名称:openduty,代码行数:22,代码来源:xmppclient.py

示例3: get_pubkey

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import PEM_cert_to_DER_cert [as 别名]
def get_pubkey(pem):
    """ Extracts public key from x08 pem. """
    der = ssl.PEM_cert_to_DER_cert(pem)

    # Extract subjectPublicKeyInfo field from X.509 certificate (see RFC3280)
    cert = DerSequence()
    cert.decode(der)
    tbsCertificate = DerSequence()
    tbsCertificate.decode(cert[0])
    subjectPublicKeyInfo = tbsCertificate[6]

    return subjectPublicKeyInfo 
开发者ID:Schibum,项目名称:sndlatr,代码行数:14,代码来源:x509.py

示例4: _check_ssl_cert

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import PEM_cert_to_DER_cert [as 别名]
def _check_ssl_cert(self):
        """Preflight the SSL certificate presented by the backend.

        This isn't 100% bulletproof, in that we're not actually validating the
        transport used to communicate with Shippo, merely that the first
        attempt to does not use a revoked certificate.

        Unfortunately the interface to OpenSSL doesn't make it easy to check
        the certificate before sending potentially sensitive data on the wire.
        This approach raises the bar for an attacker significantly."""

        from shippo.config import verify_ssl_certs

        if verify_ssl_certs and not self._CERTIFICATE_VERIFIED:
            uri = urllib.parse.urlparse(shippo.config.api_base)
            try:
                certificate = ssl.get_server_certificate(
                    (uri.hostname, uri.port or 443))
                der_cert = ssl.PEM_cert_to_DER_cert(certificate)
            except socket.error as e:
                raise error.APIConnectionError(e)
            except TypeError:
                # The Google App Engine development server blocks the C socket
                # module which causes a type error when using the SSL library
                if ('APPENGINE_RUNTIME' in os.environ and
                        'Dev' in os.environ.get('SERVER_SOFTWARE', '')):
                    self._CERTIFICATE_VERIFIED = True
                    warnings.warn(
                        'We were unable to verify Shippo\'s SSL certificate '
                        'due to a bug in the Google App Engine development '
                        'server. Please alert us immediately at '
                        'suppgoshippo.compo.com if this message appears in your '
                        'production logs.')
                    return
                else:
                    raise

            self._CERTIFICATE_VERIFIED = certificate_blacklist.verify(
                uri.hostname, der_cert) 
开发者ID:goshippo,项目名称:shippo-python-client,代码行数:41,代码来源:api_requestor.py

示例5: pair

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import PEM_cert_to_DER_cert [as 别名]
def pair(clientsocket):
    print "wants to pair"       
    mycert = open(os.path.join(configmanager.keydir, "server.crt"), "r").read()
    secure_port = str(configmanager.secure_port)

    myder_cert = ssl.PEM_cert_to_DER_cert(mycert)
    m = hashlib.sha256(myder_cert)
    myfp = m.hexdigest().upper()
    myfp = " ".join(myfp[i:i+4] for i in range(0, len(myfp), 4))
    print "\nMy SHA256: "+myfp
    #send my certiuficate
    clientsocket.sendall(myder_cert.encode('base64'))

    #receive client Certificate
    clientcert = clientsocket.recv(2048)

    m = hashlib.sha256(clientcert)
    devicefp = m.hexdigest().upper()
    devicefp = " ".join(devicefp[i:i+4] for i in range(0, len(devicefp), 4))
    print "\nClient SHA256: "+devicefp
    
    fpdiag = subprocess.Popen([PROGRAMDIR+"/fingerprints.py", myfp, devicefp], stdout=subprocess.PIPE)
    (vout, verr) = fpdiag.communicate()

    if (vout.strip()=="True"):
        clientsocket.sendall(secure_port+"\n")
    else:
        clientsocket.sendall("0\n");
        pass

    ack = clientsocket.recv(2)
    if (ack=="OK"):
        #save pub key
        with open(os.path.join(configmanager.keydir, "cas.pem"), 'a') as the_file:
            the_file.write(ssl.DER_cert_to_PEM_cert(clientcert))
        print "Successfully paired the Device!"

    else:
        print "Failed to pair Device." 
开发者ID:screenfreeze,项目名称:deskcon-desktop,代码行数:41,代码来源:authentication.py

示例6: load_PEMfile

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import PEM_cert_to_DER_cert [as 别名]
def load_PEMfile(self, certificate_path):
        """Load a certificate from a file in PEM format
        """
        self._init_data()
        self._filepath = certificate_path
        with open(self._filepath, "r") as inputFile:
            PEMdata = inputFile.read()
        # convert to binary (DER format)
        self._data = ssl.PEM_cert_to_DER_cert(PEMdata) 
开发者ID:alibaba,项目名称:iOSSecAudit,代码行数:11,代码来源:iosCertTrustManager.py

示例7: pair_client

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import PEM_cert_to_DER_cert [as 别名]
def pair_client(clientsocket, q):
    print "wants to pair"       
    mycert = open(os.path.join(configmanager.keydir, "server.crt"), "r").read()
    secure_port = str(configmanager.secure_port)

    myder_cert = ssl.PEM_cert_to_DER_cert(mycert)
    m = hashlib.sha256(myder_cert)
    myfp = m.hexdigest().upper()
    myfp = " ".join(myfp[i:i+4] for i in range(0, len(myfp), 4))
    print "\nMy SHA256: "+myfp
    #send my certiuficate
    clientsocket.sendall(myder_cert.encode('base64'))

    #receive client Certificate
    clientcert = clientsocket.recv(2048)

    m = hashlib.sha256(clientcert)
    devicefp = m.hexdigest().upper()
    devicefp = " ".join(devicefp[i:i+4] for i in range(0, len(devicefp), 4))
    print "\nClient SHA256: "+devicefp

    if (q): #GUI 
        q.put([myfp, devicefp])
        vout = q.get(True)
    else: #CMDLine only
        vout = raw_input("Do they match?(yes/no)\n") 

    if (vout.strip().lower()=="yes"):
        clientsocket.sendall(secure_port+"\n")
    else:
        clientsocket.sendall("0\n");
        pass

    print "wait for Device..."
    ack = clientsocket.recv(2)

    if (ack=="OK"):
        #save pub key
        with open(os.path.join(configmanager.keydir, "cas.pem"), 'a') as the_file:
            the_file.write(ssl.DER_cert_to_PEM_cert(clientcert))

        if (q):
            q.put(1)

        restart_server()
        print "Successfully paired the Device!"

    else:
        if (q):
            q.put(0)
        print "Failed to pair Device." 
开发者ID:screenfreeze,项目名称:deskcon-desktop,代码行数:53,代码来源:pair.py

示例8: validate_certificate

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import PEM_cert_to_DER_cert [as 别名]
def validate_certificate(host, port, certpath, certext):
    hostname = re.sub('[:.]', '_', host)
    cert_file = '%s%s%s' % (certpath, hostname, certext)
    try:
        with open(cert_file, 'r') as f:
            # Retrieve previously trusted certificate
            trusted_cert = ssl.PEM_cert_to_DER_cert(f.read())
    except Exception:
        # found no trusted certificate
        return False
    # Read current certificate from host
    conn = None
    try:
        # workaround for http://bugs.python.org/issue11811
        # should go back to using get_server_certificate when fixed
        # (Issue is resolved as of python 3.3.  Workaround still needed for
        # python 2.7 support.)
        #   rawcert = ssl.get_server_certificate((host, port))
        #   current_cert = ssl.PEM_cert_to_DER_cert(rawcert)
        conn = socket.create_connection((host, port))
        sock = ssl.wrap_socket(conn)
        current_cert = sock.getpeercert(True)
    except Exception:
        # couldn't get certificate from host
        return False
    finally:
        if conn is not None:
            conn.shutdown(socket.SHUT_RDWR)
            conn.close()
    # Verify certificate finger prints are the same
    if not (hashlib.sha1(trusted_cert).digest() ==
            hashlib.sha1(current_cert).digest()):
        return False
    # check certificate expiration
    try:
        cert = der_decoder.decode(current_cert,
                                  asn1Spec=rfc2459.Certificate())[0]
        tbs = cert.getComponentByName('tbsCertificate')
        validity = tbs.getComponentByName('validity')
        not_after = validity.getComponentByName('notAfter').getComponent()
        not_after = dt.datetime.strptime(str(not_after), '%y%m%d%H%M%SZ')
        if dt.datetime.utcnow() >= not_after:
            LOG.warning(_('Certificate has expired.'))
            return False
    except Exception:
        LOG.exception('error parsing cert for expiration check')
        return False
    return True 
开发者ID:powervm,项目名称:pypowervm,代码行数:50,代码来源:util.py


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