當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。