python类encode()的实例源码

ocsp_pyopenssl.py 文件源码 项目:snowflake-connector-python 作者: snowflakedb 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _read_ca_bundle(ca_bundle_file):
    """
    Reads a cabundle file including certificates in PEM format
    """
    logger = getLogger(__name__)
    logger.debug('reading ca cabundle: %s', ca_bundle_file)
    # cabundle file encoding varies. Tries reading it in utf-8 but ignore
    # all errors
    all_certs = codecs.open(
        ca_bundle_file, 'r', encoding='utf-8', errors='ignore').read()
    state = 0
    contents = []
    for line in all_certs.split('\n'):
        if state == 0 and line.startswith('-----BEGIN CERTIFICATE-----'):
            state = 1
            contents.append(line)
        elif state == 1:
            contents.append(line)
            if line.startswith('-----END CERTIFICATE-----'):
                cert = load_certificate(
                    FILETYPE_PEM,
                    '\n'.join(contents).encode('utf-8'))
                ROOT_CERTIFICATES_DICT[cert.get_subject().der()] = cert
                state = 0
                contents = []
securityblob.py 文件源码 项目:00scanner 作者: xiaoqin00 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def generateNegotiateSecurityBlob(ntlm_data):
    mech_token = univ.OctetString(ntlm_data).subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2))
    mech_types = MechTypeList().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))
    mech_types.setComponentByPosition(0, univ.ObjectIdentifier('1.3.6.1.4.1.311.2.2.10'))

    n = NegTokenInit().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))
    n.setComponentByName('mechTypes', mech_types)
    n.setComponentByName('mechToken', mech_token)

    nt = NegotiationToken()
    nt.setComponentByName('negTokenInit', n)

    ct = ContextToken()
    ct.setComponentByName('thisMech', univ.ObjectIdentifier('1.3.6.1.5.5.2'))
    ct.setComponentByName('innerContextToken', nt)

    return encoder.encode(ct)
rsa.py 文件源码 项目:cryptoconditions 作者: bigchaindb 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def fingerprint_contents(self):
        """Produce the contents of the condition hash.

        This function is called internally by the `getCondition` method.

        Returns:
            bytes: Encoded contents of fingerprint hash.

        """
        if self.modulus is None:
            raise MissingDataError('Requires modulus')

        asn1_obj = nat_decode({'modulus': self.modulus},
                              asn1Spec=RsaFingerprintContents())
        asn1_der = der_encode(asn1_obj)
        return asn1_der
prefix.py 文件源码 项目:cryptoconditions 作者: bigchaindb 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def fingerprint_contents(self):
        """Produce the contents of the condition hash.

        This function is called internally by the ``condition``
        method/property.

        Returns:
            bytes: Encoded contents of fingerprint hash.

        """
        if not self.subcondition:
            raise MissingDataError('Requires subcondition')

        try:
            subcondition_asn1_dict = self.subcondition.condition.to_asn1_dict()
        except AttributeError:
            subcondition_asn1_dict = self.subcondition.to_asn1_dict()

        return der_encode(nat_decode({
            'prefix': self.prefix,
            'maxMessageLength': self.max_message_length,
            'subcondition': subcondition_asn1_dict,
        }, asn1Spec=PrefixFingerprintContents()))
threshold.py 文件源码 项目:cryptoconditions 作者: bigchaindb 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def fingerprint_contents(self):
        """

        .. todo:: docs

        """
        subconditions = [
            c.to_asn1_dict() for c in sorted(
                map(lambda c: c['body']
                    if isinstance(c['body'], Condition)
                    else c['body'].condition, self.subconditions))
        ]
        asn1_fingerprint_obj = nat_decode(
            {'threshold': self.threshold, 'subconditions': subconditions},
            asn1Spec=ThresholdFingerprintContents(),
        )
        return der_encode(asn1_fingerprint_obj)
condition.py 文件源码 项目:cryptoconditions 作者: bigchaindb 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def serialize_binary(self):
        """
        Serialize condition to a buffer.

        Encodes the condition as a string of bytes. This is used internally for
        encoding subconditions, but can also be used to passing around conditions
        in a binary protocol for instance.

        CONDITION =
            VARUINT TYPE_BITMASK
            VARBYTES HASH
            VARUINT MAX_COST

        Return:
            Serialized condition
        """
        asn1_dict = self.to_asn1_dict()
        asn1_condition = nat_decode(asn1_dict, asn1Spec=Asn1Condition())
        binary_condition = der_encode(asn1_condition)
        return binary_condition
ssh_gss.py 文件源码 项目:RemoteTree 作者: deNULL 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def ssh_gss_oids(self, mode="client"):
        """
        This method returns a single OID, because we only support the
        Kerberos V5 mechanism.

        :param str mode: Client for client mode and server for server mode
        :return: A byte sequence containing the number of supported
                 OIDs, the length of the OID and the actual OID encoded with
                 DER
        :note: In server mode we just return the OID length and the DER encoded
               OID.
        """
        OIDs = self._make_uint32(1)
        krb5_OID = encoder.encode(ObjectIdentifier(self._krb5_mech))
        OID_len = self._make_uint32(len(krb5_OID))
        if mode == "server":
            return OID_len + krb5_OID
        return OIDs + OID_len + krb5_OID
securityblob.py 文件源码 项目:xunfengES 作者: superhuahua 项目源码 文件源码 阅读 52 收藏 0 点赞 0 评论 0
def generateNegotiateSecurityBlob(ntlm_data):
    mech_token = univ.OctetString(ntlm_data).subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2))
    mech_types = MechTypeList().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))
    mech_types.setComponentByPosition(0, univ.ObjectIdentifier('1.3.6.1.4.1.311.2.2.10'))

    n = NegTokenInit().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))
    n.setComponentByName('mechTypes', mech_types)
    n.setComponentByName('mechToken', mech_token)

    nt = NegotiationToken()
    nt.setComponentByName('negTokenInit', n)

    ct = ContextToken()
    ct.setComponentByName('thisMech', univ.ObjectIdentifier('1.3.6.1.5.5.2'))
    ct.setComponentByName('innerContextToken', nt)

    return encoder.encode(ct)
securityblob.py 文件源码 项目:xunfengES 作者: superhuahua 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def generateNegotiateSecurityBlob(ntlm_data):
    mech_token = univ.OctetString(ntlm_data).subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2))
    mech_types = MechTypeList().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))
    mech_types.setComponentByPosition(0, univ.ObjectIdentifier('1.3.6.1.4.1.311.2.2.10'))

    n = NegTokenInit().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))
    n.setComponentByName('mechTypes', mech_types)
    n.setComponentByName('mechToken', mech_token)

    nt = NegotiationToken()
    nt.setComponentByName('negTokenInit', n)

    ct = ContextToken()
    ct.setComponentByName('thisMech', univ.ObjectIdentifier('1.3.6.1.5.5.2'))
    ct.setComponentByName('innerContextToken', nt)

    return encoder.encode(ct)
securityblob.py 文件源码 项目:addon 作者: alfa-addon 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def generateNegotiateSecurityBlob(ntlm_data):
    mech_token = univ.OctetString(ntlm_data).subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2))
    mech_types = MechTypeList().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))
    mech_types.setComponentByPosition(0, univ.ObjectIdentifier('1.3.6.1.4.1.311.2.2.10'))

    n = NegTokenInit().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))
    n.setComponentByName('mechTypes', mech_types)
    n.setComponentByName('mechToken', mech_token)

    nt = NegotiationToken()
    nt.setComponentByName('negTokenInit', n)

    ct = ContextToken()
    ct.setComponentByName('thisMech', univ.ObjectIdentifier('1.3.6.1.5.5.2'))
    ct.setComponentByName('innerContextToken', nt)

    return encoder.encode(ct)
key.py 文件源码 项目:oscars2016 作者: 0x0ece 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _save_pkcs1_der(self):
        '''Saves the public key in PKCS#1 DER format.

        @returns: the DER-encoded public key.
        '''

        from pyasn1.codec.der import encoder
        from rsa.asn1 import AsnPubKey

        # Create the ASN object
        asn_key = AsnPubKey()
        asn_key.setComponentByName('modulus', self.n)
        asn_key.setComponentByName('publicExponent', self.e)

        return encoder.encode(asn_key)
key.py 文件源码 项目:oscars2016 作者: 0x0ece 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _save_pkcs1_der(self):
        '''Saves the private key in PKCS#1 DER format.

        @returns: the DER-encoded private key.
        '''

        from pyasn1.type import univ, namedtype
        from pyasn1.codec.der import encoder

        class AsnPrivKey(univ.Sequence):
            componentType = namedtype.NamedTypes(
                namedtype.NamedType('version', univ.Integer()),
                namedtype.NamedType('modulus', univ.Integer()),
                namedtype.NamedType('publicExponent', univ.Integer()),
                namedtype.NamedType('privateExponent', univ.Integer()),
                namedtype.NamedType('prime1', univ.Integer()),
                namedtype.NamedType('prime2', univ.Integer()),
                namedtype.NamedType('exponent1', univ.Integer()),
                namedtype.NamedType('exponent2', univ.Integer()),
                namedtype.NamedType('coefficient', univ.Integer()),
            )

        # Create the ASN object
        asn_key = AsnPrivKey()
        asn_key.setComponentByName('version', 0)
        asn_key.setComponentByName('modulus', self.n)
        asn_key.setComponentByName('publicExponent', self.e)
        asn_key.setComponentByName('privateExponent', self.d)
        asn_key.setComponentByName('prime1', self.p)
        asn_key.setComponentByName('prime2', self.q)
        asn_key.setComponentByName('exponent1', self.exp1)
        asn_key.setComponentByName('exponent2', self.exp2)
        asn_key.setComponentByName('coefficient', self.coef)

        return encoder.encode(asn_key)
krb5.py 文件源码 项目:kerberom 作者: Synacktiv 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def build_ap_req(ticket, key, msg_type, authenticator):
    enc_auth = encrypt(key[0], key[1], msg_type, encode(authenticator))

    ap_req = APReq()
    ap_req['pvno'] = 5
    ap_req['msg-type'] = 14
    ap_req['ap-options'] = "'00000000000000000000000000000000'B"
    ap_req['ticket'] = _v(3, ticket)

    ap_req['authenticator'] = None
    ap_req['authenticator']['etype'] = key[0]
    ap_req['authenticator']['cipher'] = enc_auth

    return ap_req
krb5.py 文件源码 项目:kerberom 作者: Synacktiv 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def build_pa_enc_timestamp(current_time, key):
    gt, ms = epoch2gt(current_time, microseconds=True)
    pa_ts_enc = PaEncTsEnc()
    pa_ts_enc['patimestamp'] = gt
    pa_ts_enc['pausec'] = ms

    pa_ts = PaEncTimestamp()
    pa_ts['etype'] = key[0]
    pa_ts['cipher'] = encrypt(key[0], key[1], 1, encode(pa_ts_enc))

    return pa_ts
krb5.py 文件源码 项目:kerberom 作者: Synacktiv 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def send_req(req, kdc, port=88):
    data = encode(req)
    data = pack('>I', len(data)) + data
    sock = socket()
    sock.connect((kdc, port))
    sock.send(data)
    return sock
utils.py 文件源码 项目:noc-orchestrator 作者: DirceuSilvaLabs 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def encode_dss_signature(r, s):
    if (
        not isinstance(r, six.integer_types) or
        not isinstance(s, six.integer_types)
    ):
        raise ValueError("Both r and s must be integers")

    sig = _DSSSigValue()
    sig.setComponentByName('r', r)
    sig.setComponentByName('s', s)
    return encoder.encode(sig)
utils.py 文件源码 项目:noc-orchestrator 作者: DirceuSilvaLabs 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def encode_dss_signature(r, s):
    if (
        not isinstance(r, six.integer_types) or
        not isinstance(s, six.integer_types)
    ):
        raise ValueError("Both r and s must be integers")

    sig = _DSSSigValue()
    sig.setComponentByName('r', r)
    sig.setComponentByName('s', s)
    return encoder.encode(sig)
key.py 文件源码 项目:GAMADV-XTD 作者: taers232c 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def _save_pkcs1_der(self):
        """Saves the public key in PKCS#1 DER format.

        @returns: the DER-encoded public key.
        """

        from pyasn1.codec.der import encoder
        from rsa.asn1 import AsnPubKey

        # Create the ASN object
        asn_key = AsnPubKey()
        asn_key.setComponentByName('modulus', self.n)
        asn_key.setComponentByName('publicExponent', self.e)

        return encoder.encode(asn_key)
key.py 文件源码 项目:GAMADV-XTD 作者: taers232c 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _save_pkcs1_der(self):
        """Saves the private key in PKCS#1 DER format.

        @returns: the DER-encoded private key.
        """

        from pyasn1.type import univ, namedtype
        from pyasn1.codec.der import encoder

        class AsnPrivKey(univ.Sequence):
            componentType = namedtype.NamedTypes(
                    namedtype.NamedType('version', univ.Integer()),
                    namedtype.NamedType('modulus', univ.Integer()),
                    namedtype.NamedType('publicExponent', univ.Integer()),
                    namedtype.NamedType('privateExponent', univ.Integer()),
                    namedtype.NamedType('prime1', univ.Integer()),
                    namedtype.NamedType('prime2', univ.Integer()),
                    namedtype.NamedType('exponent1', univ.Integer()),
                    namedtype.NamedType('exponent2', univ.Integer()),
                    namedtype.NamedType('coefficient', univ.Integer()),
            )

        # Create the ASN object
        asn_key = AsnPrivKey()
        asn_key.setComponentByName('version', 0)
        asn_key.setComponentByName('modulus', self.n)
        asn_key.setComponentByName('publicExponent', self.e)
        asn_key.setComponentByName('privateExponent', self.d)
        asn_key.setComponentByName('prime1', self.p)
        asn_key.setComponentByName('prime2', self.q)
        asn_key.setComponentByName('exponent1', self.exp1)
        asn_key.setComponentByName('exponent2', self.exp2)
        asn_key.setComponentByName('coefficient', self.coef)

        return encoder.encode(asn_key)
auth_data.py 文件源码 项目:srepp_server 作者: SummitRoute 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def _ParseAuthAttrs(self, auth_attrs, required):
    results = dict.fromkeys(required)
    for attr in auth_attrs:
      if (attr['type'] in oids.OID_TO_CLASS and
          oids.OID_TO_CLASS.get(attr['type']) in required):
        # There are more than those I require, but I don't know what they are,
        # and what to do with them. The spec does not talk about them.
        # One example:
        # 1.3.6.1.4.1.311.2.1.11 contains as value 1.3.6.1.4.1.311.2.1.21
        # SPC_STATEMENT_TYPE_OBJID    SPC_INDIVIDUAL_SP_KEY_PURPOSE_OBJID
        results[oids.OID_TO_CLASS.get(attr['type'])] = attr['values']
    if None in results.itervalues():
      raise Asn1Error('Missing mandatory field(s) in auth_attrs.')

    # making sure that the auth_attrs were processed in correct order
    # they need to be sorted in ascending order in the SET, when DER encoded
    # This also makes sure that the tag on Attributes is correct.
    a = [der_encoder.encode(i) for i in auth_attrs]
    a.sort()
    attrs_for_hash = pkcs7.Attributes()
    for i in range(len(auth_attrs)):
      d, _ = decoder.decode(a[i], asn1Spec=pkcs7.Attribute())
      attrs_for_hash.setComponentByPosition(i, d)
    encoded_attrs = der_encoder.encode(attrs_for_hash)

    return results, encoded_attrs


问题


面经


文章

微信
公众号

扫码关注公众号