當前位置: 首頁>>代碼示例>>Python>>正文


Python rfc2459.Certificate方法代碼示例

本文整理匯總了Python中pyasn1_modules.rfc2459.Certificate方法的典型用法代碼示例。如果您正苦於以下問題:Python rfc2459.Certificate方法的具體用法?Python rfc2459.Certificate怎麽用?Python rfc2459.Certificate使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pyasn1_modules.rfc2459的用法示例。


在下文中一共展示了rfc2459.Certificate方法的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: parse_cert

# 需要導入模塊: from pyasn1_modules import rfc2459 [as 別名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 別名]
def parse_cert(raw_bytes):
    result = CertInfo()

    certType = rfc2459.Certificate(); 
    cert, rest = decoder.decode(raw_bytes, asn1Spec=certType)
    subj_pub_key_bytes = frombits(cert.getComponentByName('tbsCertificate').getComponentByName('subjectPublicKeyInfo').getComponentByName('subjectPublicKey'))
    SUBJECT = cert.getComponentByName('tbsCertificate').getComponentByName('subject')
    for rdn in SUBJECT[0]:
        for nv in rdn: 
            name = nv.getComponentByName('type')
            value = nv.getComponentByName('value')
            # could pick up regular OUs too
            if name == rfc2459.id_at_organizationalUnitName:
                #print 'name: %s' % name
                #print 'value: [%s] (%s)' % (str(value).strip(), type(value))
                result.control_fields.append(str(value).strip())

    rsaType = rfc2437.RSAPublicKey();
    rsadata,rsadata_rest = decoder.decode(subj_pub_key_bytes, asn1Spec=rsaType)
    mod = rsadata.getComponentByName("modulus")
    pub_exp = rsadata.getComponentByName("publicExponent")
    result.pub_key = rsa.PublicKey(long(mod), long(pub_exp))

    return result 
開發者ID:nelenkov,項目名稱:aboot-parser,代碼行數:26,代碼來源:parse-aboot.py

示例2: value

# 需要導入模塊: from pyasn1_modules import rfc2459 [as 別名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 別名]
def value(self):
        val = b""

        for k in self.field.keys():
            ln = b""
            dim = b""
            if (len(self.field[k])):
                ln += k.encode('utf-8') + b";DNS:"
                for v in self.field[k]:
                    ln += dim + v.encode('utf-8')
                    dim = b"," + k.encode('utf-8') + b";DNS:"
                val += (b"" if val == b"" else b",") + ln

        return val

# Certificate modifier class that holds callback functions that alter the behavior
# of the certificate generation logic at different stages 
開發者ID:yymax,項目名稱:x509test,代碼行數:19,代碼來源:Certificate.py

示例3: setUp

# 需要導入模塊: from pyasn1_modules import rfc2459 [as 別名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 別名]
def setUp(self):
        self.asn1Spec = rfc2459.Certificate() 
開發者ID:etingof,項目名稱:pyasn1-modules,代碼行數:4,代碼來源:test_rfc2459.py

示例4: from_string

# 需要導入模塊: from pyasn1_modules import rfc2459 [as 別名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 別名]
def from_string(cls, public_key):
        """Construct an Verifier instance from a public key or public
        certificate string.

        Args:
            public_key (Union[str, bytes]): The public key in PEM format or the
                x509 public key certificate.

        Returns:
            Verifier: The constructed verifier.

        Raises:
            ValueError: If the public_key can't be parsed.
        """
        public_key = _helpers.to_bytes(public_key)
        is_x509_cert = _CERTIFICATE_MARKER in public_key

        # If this is a certificate, extract the public key info.
        if is_x509_cert:
            der = rsa.pem.load_pem(public_key, "CERTIFICATE")
            asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate())
            if remaining != b"":
                raise ValueError("Unused bytes", remaining)

            cert_info = asn1_cert["tbsCertificate"]["subjectPublicKeyInfo"]
            key_bytes = _bit_list_to_bytes(cert_info["subjectPublicKey"])
            pubkey = rsa.PublicKey.load_pkcs1(key_bytes, "DER")
        else:
            pubkey = rsa.PublicKey.load_pkcs1(public_key, "PEM")
        return cls(pubkey) 
開發者ID:googleapis,項目名稱:google-auth-library-python,代碼行數:32,代碼來源:_python_rsa.py

示例5: from_string

# 需要導入模塊: from pyasn1_modules import rfc2459 [as 別名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 別名]
def from_string(cls, key_pem, is_x509_cert):
        """Construct an RsaVerifier 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:
            RsaVerifier instance.

        Raises:
            ValueError: if the key_pem can't be parsed. In either case, error
                        will begin with 'No PEM start marker'. If
                        ``is_x509_cert`` is True, will fail to find the
                        "-----BEGIN CERTIFICATE-----" error, otherwise fails
                        to find "-----BEGIN RSA PUBLIC KEY-----".
        """
        key_pem = _to_bytes(key_pem)
        if is_x509_cert:
            der = rsa.pem.load_pem(key_pem, 'CERTIFICATE')
            asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate())
            if remaining != b'':
                raise ValueError('Unused bytes', remaining)

            cert_info = asn1_cert['tbsCertificate']['subjectPublicKeyInfo']
            key_bytes = _bit_list_to_bytes(cert_info['subjectPublicKey'])
            pubkey = rsa.PublicKey.load_pkcs1(key_bytes, 'DER')
        else:
            pubkey = rsa.PublicKey.load_pkcs1(key_pem, 'PEM')
        return cls(pubkey) 
開發者ID:Deltares,項目名稱:aqua-monitor,代碼行數:33,代碼來源:_pure_python_crypt.py

示例6: from_string

# 需要導入模塊: from pyasn1_modules import rfc2459 [as 別名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 別名]
def from_string(cls, key_pem, is_x509_cert):
        """Construct an RsaVerifier 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:
            RsaVerifier instance.

        Raises:
            ValueError: if the key_pem can't be parsed. In either case, error
                        will begin with 'No PEM start marker'. If
                        ``is_x509_cert`` is True, will fail to find the
                        "-----BEGIN CERTIFICATE-----" error, otherwise fails
                        to find "-----BEGIN RSA PUBLIC KEY-----".
        """
        key_pem = _helpers._to_bytes(key_pem)
        if is_x509_cert:
            der = rsa.pem.load_pem(key_pem, 'CERTIFICATE')
            asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate())
            if remaining != b'':
                raise ValueError('Unused bytes', remaining)

            cert_info = asn1_cert['tbsCertificate']['subjectPublicKeyInfo']
            key_bytes = _bit_list_to_bytes(cert_info['subjectPublicKey'])
            pubkey = rsa.PublicKey.load_pkcs1(key_bytes, 'DER')
        else:
            pubkey = rsa.PublicKey.load_pkcs1(key_pem, 'PEM')
        return cls(pubkey) 
開發者ID:fniephaus,項目名稱:alfred-gmail,代碼行數:33,代碼來源:_pure_python_crypt.py

示例7: from_string

# 需要導入模塊: from pyasn1_modules import rfc2459 [as 別名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 別名]
def from_string(cls, public_key):
        """Construct an Verifier instance from a public key or public
        certificate string.

        Args:
            public_key (Union[str, bytes]): The public key in PEM format or the
                x509 public key certificate.

        Returns:
            Verifier: The constructed verifier.

        Raises:
            ValueError: If the public_key can't be parsed.
        """
        public_key = _helpers.to_bytes(public_key)
        is_x509_cert = _CERTIFICATE_MARKER in public_key

        # If this is a certificate, extract the public key info.
        if is_x509_cert:
            der = rsa.pem.load_pem(public_key, 'CERTIFICATE')
            asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate())
            if remaining != b'':
                raise ValueError('Unused bytes', remaining)

            cert_info = asn1_cert['tbsCertificate']['subjectPublicKeyInfo']
            key_bytes = _bit_list_to_bytes(cert_info['subjectPublicKey'])
            pubkey = rsa.PublicKey.load_pkcs1(key_bytes, 'DER')
        else:
            pubkey = rsa.PublicKey.load_pkcs1(public_key, 'PEM')
        return cls(pubkey) 
開發者ID:fniephaus,項目名稱:alfred-gmail,代碼行數:32,代碼來源:_python_rsa.py

示例8: _PopulateX509

# 需要導入模塊: from pyasn1_modules import rfc2459 [as 別名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 別名]
def _PopulateX509(self):
    with self._x509_init_lock:
      if self._x509 is None:

        url = ('https://www.googleapis.com/service_accounts/v1/metadata/x509/%s'
               % urllib.unquote_plus(self._credentials.service_account_email))
        response = urlfetch.fetch(
            url=url,
            validate_certificate=True,
            method=urlfetch.GET)
        if response.status_code != 200:
          raise apiproxy_errors.ApplicationError(
              app_identity_service_pb.AppIdentityServiceError.UNKNOWN_ERROR,
              'Unable to load X509 cert: %s Response code: %i, Content: %s' % (
                  url, response.status_code, response.content))

        message = 'dummy'
        _, signature = self._credentials.sign_blob(message)

        for signing_key, x509 in json.loads(response.content).items():
          der = rsa.pem.load_pem(x509, 'CERTIFICATE')
          asn1_cert, _ = decoder.decode(der, asn1Spec=Certificate())

          key_bitstring = (
              asn1_cert['tbsCertificate']
              ['subjectPublicKeyInfo']
              ['subjectPublicKey'])
          key_bytearray = BitStringToByteString(key_bitstring)

          public_key = rsa.PublicKey.load_pkcs1(key_bytearray, 'DER')
          try:
            if rsa.pkcs1.verify(message, signature, public_key):
              self._x509 = x509
              self._signing_key = signing_key
              return
          except rsa.pkcs1.VerificationError:
            pass

        raise apiproxy_errors.ApplicationError(
            app_identity_service_pb.AppIdentityServiceError.UNKNOWN_ERROR,
            'Unable to find matching X509 cert for private key: %s' % url) 
開發者ID:GoogleCloudPlatform,項目名稱:python-compat-runtime,代碼行數:43,代碼來源:app_identity_defaultcredentialsbased_stub.py

示例9: getSubject

# 需要導入模塊: from pyasn1_modules import rfc2459 [as 別名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 別名]
def getSubject(self):
        subj = crypto.X509().get_subject()
        subj.C = self.country
        subj.ST = self.state
        subj.L = self.city
        subj.O = self.org
        subj.OU = self.unit
        subj.CN = self.commonName
        subj.emailAddress = self.email

        return subj

# Certificate key class that represents the public/private key pair. 
開發者ID:yymax,項目名稱:x509test,代碼行數:15,代碼來源:Certificate.py

示例10: build

# 需要導入模塊: from pyasn1_modules import rfc2459 [as 別名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 別名]
def build(self):
        if (not self.key):
            self.key = crypto.PKey()
            self.key.generate_key(self.kType, self.kSize)

        return self

# Certificate security class that holds the subject public key and
# other miscellaneous information. 
開發者ID:yymax,項目名稱:x509test,代碼行數:11,代碼來源:Certificate.py

示例11: postWrite

# 需要導入模塊: from pyasn1_modules import rfc2459 [as 別名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 別名]
def postWrite(self, cert, certPathPrefix):
        return None

# Certificate class that represents a X509 certificate 
開發者ID:yymax,項目名稱:x509test,代碼行數:6,代碼來源:Certificate.py

示例12: validate_certificate

# 需要導入模塊: from pyasn1_modules import rfc2459 [as 別名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [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

示例13: _PopulateX509

# 需要導入模塊: from pyasn1_modules import rfc2459 [as 別名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 別名]
def _PopulateX509(self):
    with self.__x509_init_lock:
      if not self.__x509:
        url = ('https://www.googleapis.com/service_accounts/v1/metadata/x509/%s'
               % urllib.unquote_plus(self.__email_address))
        resp = urlfetch.fetch(
            url=url,
            validate_certificate=True,
            method=urlfetch.GET)
        if resp.status_code != 200:
          raise apiproxy_errors.ApplicationError(
              app_identity_service_pb.AppIdentityServiceError.UNKNOWN_ERROR,
              'Unable to load X509 cert: %s Response code: %i, Content: %s' % (
                  url, resp.status_code, resp.content))

        msg = 'test'
        sig = rsa.pkcs1.sign(msg, self.__private_key, 'SHA-256')




        for signing_key, x509 in json.loads(resp.content).items():
          der = rsa.pem.load_pem(x509, 'CERTIFICATE')
          asn1_cert, _ = decoder.decode(der, asn1Spec=Certificate())

          key_bitstring = (
              asn1_cert['tbsCertificate']
              ['subjectPublicKeyInfo']
              ['subjectPublicKey'])
          key_bytearray = BitStringToByteString(key_bitstring)

          pub = rsa.PublicKey.load_pkcs1(key_bytearray, 'DER')
          try:
            if rsa.pkcs1.verify(msg, sig, pub):
              self.__x509 = x509
              self.__signing_key = signing_key
              return
          except rsa.pkcs1.VerificationError:
            pass


        raise apiproxy_errors.ApplicationError(
            app_identity_service_pb.AppIdentityServiceError.UNKNOWN_ERROR,
            'Unable to find matching X509 cert for private key: %s' % url) 
開發者ID:GoogleCloudPlatform,項目名稱:python-compat-runtime,代碼行數:46,代碼來源:app_identity_keybased_stub.py


注:本文中的pyasn1_modules.rfc2459.Certificate方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。