Python pyasn1.error 模块,PyAsn1Error() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pyasn1.error.PyAsn1Error()

项目:oscars2016    作者:0x0ece    | 项目源码 | 文件源码
def prettyIn(self, value):
        if not isinstance(value, str):
            try:
                return int(value)
            except:
                raise error.PyAsn1Error(
                    'Can\'t coerce %r into integer: %s' % (value, sys.exc_info()[1])
                    )
        r = self.__namedValues.getValue(value)
        if r is not None:
            return r
        try:
            return int(value)
        except:
            raise error.PyAsn1Error(
                'Can\'t coerce %r into integer: %s' % (value, sys.exc_info()[1])
                )
项目:oscars2016    作者:0x0ece    | 项目源码 | 文件源码
def prettyIn(self, value):
            if isinstance(value, str):
                return value
            elif isinstance(value, unicode):
                try:
                    return value.encode(self._encoding)
                except (LookupError, UnicodeEncodeError):
                    raise error.PyAsn1Error(
                        'Can\'t encode string \'%s\' with \'%s\' codec' % (value, self._encoding)
                    )
            elif isinstance(value, (tuple, list)):
                try:
                    return ''.join([ chr(x) for x in value ])
                except ValueError:
                    raise error.PyAsn1Error(
                        'Bad OctetString initializer \'%s\'' % (value,)
                    )                
            else:
                return str(value)
项目:oscars2016    作者:0x0ece    | 项目源码 | 文件源码
def fromBinaryString(self, value):
        bitNo = 8; byte = 0; r = ()
        for v in value:
            if bitNo:
                bitNo = bitNo - 1
            else:
                bitNo = 7
                r = r + (byte,)
                byte = 0
            if v == '0':
                v = 0
            elif v == '1':
                v = 1
            else:
                raise error.PyAsn1Error(
                    'Non-binary OCTET STRING initializer %s' % (v,)
                    )
            byte = byte | (v << bitNo)
        return octets.ints2octs(r + (byte,))
项目:oscars2016    作者:0x0ece    | 项目源码 | 文件源码
def _cloneComponentValues(self, myClone, cloneValueFlag):
        try:
            c = self.getComponent()
        except error.PyAsn1Error:
            pass
        else:
            if isinstance(c, Choice):
                tagSet = c.getEffectiveTagSet()
            else:
                tagSet = c.getTagSet()
            if isinstance(c, base.AbstractConstructedAsn1Item):
                myClone.setComponentByType(
                    tagSet, c.clone(cloneValueFlag=cloneValueFlag)
                    )
            else:
                myClone.setComponentByType(tagSet, c.clone())
项目:oscars2016    作者:0x0ece    | 项目源码 | 文件源码
def clone(self, parentType, tagMap, uniq=False):
        if self.__defType is not None and tagMap.getDef() is not None:
            raise error.PyAsn1Error('Duplicate default value at %s' % (self,))
        if tagMap.getDef() is not None:
            defType = tagMap.getDef()
        else:
            defType = self.__defType

        posMap = self.__posMap.copy()
        for k in tagMap.getPosMap():
            if uniq and k in posMap:
                raise error.PyAsn1Error('Duplicate positive key %s' % (k,))
            posMap[k] = parentType

        negMap = self.__negMap.copy()
        negMap.update(tagMap.getNegMap())

        return self.__class__(
            posMap, negMap, defType,
            )
项目:oscars2016    作者:0x0ece    | 项目源码 | 文件源码
def __init__(self, *namedValues):
        self.nameToValIdx = {}; self.valToNameIdx = {}
        self.namedValues = ()        
        automaticVal = 1
        for namedValue in namedValues:
            if isinstance(namedValue, tuple):
                name, val = namedValue
            else:
                name = namedValue
                val = automaticVal
            if name in self.nameToValIdx:
                raise error.PyAsn1Error('Duplicate name %s' % (name,))
            self.nameToValIdx[name] = val
            if val in self.valToNameIdx:
                raise error.PyAsn1Error('Duplicate value %s=%s' % (name, val))
            self.valToNameIdx[val] = name
            self.namedValues = self.namedValues + ((name, val),)
            automaticVal = automaticVal + 1
项目:oscars2016    作者:0x0ece    | 项目源码 | 文件源码
def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length,
                     state, decodeFun, substrateFun):
        head, tail = substrate[:length], substrate[length:]
        if not head or length != 1:
            raise error.PyAsn1Error('Not single-octet Boolean payload')
        byte = oct2int(head[0])
        # CER/DER specifies encoding of TRUE as 0xFF and FALSE as 0x0, while
        # BER allows any non-zero value as TRUE; cf. sections 8.2.2. and 11.1 
        # in http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf
        if byte == 0xff:
            value = 1
        elif byte == 0x00:
            value = 0
        else:
            raise error.PyAsn1Error('Unexpected Boolean payload: %s' % byte)
        return self._createComponent(asn1Spec, tagSet, value), tail
项目:oscars2016    作者:0x0ece    | 项目源码 | 文件源码
def indefLenValueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet,
                     length, state, decodeFun, substrateFun):
        r = self._createComponent(asn1Spec, tagSet)
        if substrateFun:
            return substrateFun(r, substrate, length)
        if r.getTagSet() == tagSet: # explicitly tagged Choice
            component, substrate = decodeFun(substrate, r.getComponentTagMap())
            # eat up EOO marker
            eooMarker, substrate = decodeFun(substrate, allowEoo=True)
            if not eoo.endOfOctets.isSameTypeWith(eooMarker) or \
                    eooMarker != eoo.endOfOctets:
                raise error.PyAsn1Error('No EOO seen before substrate ends')
        else:
            component, substrate= decodeFun(
                substrate, r.getComponentTagMap(), tagSet, length, state
            )
        if isinstance(component, univ.Choice):
            effectiveTagSet = component.getEffectiveTagSet()
        else:
            effectiveTagSet = component.getTagSet()
        r.setComponentByType(effectiveTagSet, component, 0, asn1Spec is None)
        return r, substrate
项目:oscars2016    作者:0x0ece    | 项目源码 | 文件源码
def __call__(self, value, defMode=True, maxChunkSize=0):
        if not defMode and not self.supportIndefLength:
            raise error.PyAsn1Error('Indefinite length encoding not supported by this codec')
        debug.logger & debug.flagEncoder and debug.logger('encoder called in %sdef mode, chunk size %s for type %s, value:\n%s' % (not defMode and 'in' or '', maxChunkSize, value.prettyPrintType(), value.prettyPrint()))
        tagSet = value.getTagSet()
        if len(tagSet) > 1:
            concreteEncoder = explicitlyTaggedItemEncoder
        else:
            if value.typeId is not None and value.typeId in self.__typeMap:
                concreteEncoder = self.__typeMap[value.typeId]
            elif tagSet in self.__tagMap:
                concreteEncoder = self.__tagMap[tagSet]
            else:
                tagSet = value.baseTagSet
                if tagSet in self.__tagMap:
                    concreteEncoder = self.__tagMap[tagSet]
                else:
                    raise Error('No encoder for %s' % (value,))
        debug.logger & debug.flagEncoder and debug.logger('using value codec %s chosen by %s' % (concreteEncoder.__class__.__name__, tagSet))
        substrate = concreteEncoder.encode(
            self, value, defMode, maxChunkSize
            )
        debug.logger & debug.flagEncoder and debug.logger('built %s octets of substrate: %s\nencoder completed' % (len(substrate), debug.hexdump(substrate)))
        return substrate
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def prettyIn(self, value):
        if not isinstance(value, str):
            try:
                return int(value)
            except:
                raise error.PyAsn1Error(
                    'Can\'t coerce %r into integer: %s' % (value, sys.exc_info()[1])
                    )
        r = self.__namedValues.getValue(value)
        if r is not None:
            return r
        try:
            return int(value)
        except:
            raise error.PyAsn1Error(
                'Can\'t coerce %r into integer: %s' % (value, sys.exc_info()[1])
                )
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def prettyIn(self, value):
            if isinstance(value, str):
                return value
            elif isinstance(value, unicode):
                try:
                    return value.encode(self._encoding)
                except (LookupError, UnicodeEncodeError):
                    raise error.PyAsn1Error(
                        'Can\'t encode string \'%s\' with \'%s\' codec' % (value, self._encoding)
                    )
            elif isinstance(value, (tuple, list)):
                try:
                    return ''.join([ chr(x) for x in value ])
                except ValueError:
                    raise error.PyAsn1Error(
                        'Bad OctetString initializer \'%s\'' % (value,)
                    )                
            else:
                return str(value)
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def _cloneComponentValues(self, myClone, cloneValueFlag):
        try:
            c = self.getComponent()
        except error.PyAsn1Error:
            pass
        else:
            if isinstance(c, Choice):
                tagSet = c.getEffectiveTagSet()
            else:
                tagSet = c.getTagSet()
            if isinstance(c, base.AbstractConstructedAsn1Item):
                myClone.setComponentByType(
                    tagSet, c.clone(cloneValueFlag=cloneValueFlag)
                    )
            else:
                myClone.setComponentByType(tagSet, c.clone())
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def clone(self, parentType, tagMap, uniq=False):
        if self.__defType is not None and tagMap.getDef() is not None:
            raise error.PyAsn1Error('Duplicate default value at %s' % (self,))
        if tagMap.getDef() is not None:
            defType = tagMap.getDef()
        else:
            defType = self.__defType

        posMap = self.__posMap.copy()
        for k in tagMap.getPosMap():
            if uniq and k in posMap:
                raise error.PyAsn1Error('Duplicate positive key %s' % (k,))
            posMap[k] = parentType

        negMap = self.__negMap.copy()
        negMap.update(tagMap.getNegMap())

        return self.__class__(
            posMap, negMap, defType,
            )
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def __init__(self, *namedValues):
        self.nameToValIdx = {}; self.valToNameIdx = {}
        self.namedValues = ()        
        automaticVal = 1
        for namedValue in namedValues:
            if isinstance(namedValue, tuple):
                name, val = namedValue
            else:
                name = namedValue
                val = automaticVal
            if name in self.nameToValIdx:
                raise error.PyAsn1Error('Duplicate name %s' % (name,))
            self.nameToValIdx[name] = val
            if val in self.valToNameIdx:
                raise error.PyAsn1Error('Duplicate value %s=%s' % (name, val))
            self.valToNameIdx[val] = name
            self.namedValues = self.namedValues + ((name, val),)
            automaticVal = automaticVal + 1
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length,
                     state, decodeFun, substrateFun):
        head, tail = substrate[:length], substrate[length:]
        if not head or length != 1:
            raise error.PyAsn1Error('Not single-octet Boolean payload')
        byte = oct2int(head[0])
        # CER/DER specifies encoding of TRUE as 0xFF and FALSE as 0x0, while
        # BER allows any non-zero value as TRUE; cf. sections 8.2.2. and 11.1 
        # in http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf
        if byte == 0xff:
            value = 1
        elif byte == 0x00:
            value = 0
        else:
            raise error.PyAsn1Error('Unexpected Boolean payload: %s' % byte)
        return self._createComponent(asn1Spec, tagSet, value), tail
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def indefLenValueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet,
                     length, state, decodeFun, substrateFun):
        r = self._createComponent(asn1Spec, tagSet)
        if substrateFun:
            return substrateFun(r, substrate, length)
        if r.getTagSet() == tagSet: # explicitly tagged Choice
            component, substrate = decodeFun(substrate, r.getComponentTagMap())
            # eat up EOO marker
            eooMarker, substrate = decodeFun(substrate, allowEoo=True)
            if not eoo.endOfOctets.isSameTypeWith(eooMarker) or \
                    eooMarker != eoo.endOfOctets:
                raise error.PyAsn1Error('No EOO seen before substrate ends')
        else:
            component, substrate= decodeFun(
                substrate, r.getComponentTagMap(), tagSet, length, state
            )
        if isinstance(component, univ.Choice):
            effectiveTagSet = component.getEffectiveTagSet()
        else:
            effectiveTagSet = component.getTagSet()
        r.setComponentByType(effectiveTagSet, component, 0, asn1Spec is None)
        return r, substrate
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def __call__(self, value, defMode=True, maxChunkSize=0):
        if not defMode and not self.supportIndefLength:
            raise error.PyAsn1Error('Indefinite length encoding not supported by this codec')
        debug.logger & debug.flagEncoder and debug.logger('encoder called in %sdef mode, chunk size %s for type %s, value:\n%s' % (not defMode and 'in' or '', maxChunkSize, value.prettyPrintType(), value.prettyPrint()))
        tagSet = value.getTagSet()
        if len(tagSet) > 1:
            concreteEncoder = explicitlyTaggedItemEncoder
        else:
            if value.typeId is not None and value.typeId in self.__typeMap:
                concreteEncoder = self.__typeMap[value.typeId]
            elif tagSet in self.__tagMap:
                concreteEncoder = self.__tagMap[tagSet]
            else:
                tagSet = value.baseTagSet
                if tagSet in self.__tagMap:
                    concreteEncoder = self.__tagMap[tagSet]
                else:
                    raise Error('No encoder for %s' % (value,))
        debug.logger & debug.flagEncoder and debug.logger('using value codec %s chosen by %s' % (concreteEncoder.__class__.__name__, tagSet))
        substrate = concreteEncoder.encode(
            self, value, defMode, maxChunkSize
            )
        debug.logger & debug.flagEncoder and debug.logger('built %s octets of substrate: %s\nencoder completed' % (len(substrate), debug.hexdump(substrate)))
        return substrate
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def prettyIn(self, value):
            if isinstance(value, str):
                return value
            elif isinstance(value, unicode):
                try:
                    return value.encode(self.encoding)
                except (LookupError, UnicodeEncodeError):
                    raise error.PyAsn1Error(
                        "Can't encode string '%s' with codec %s" % (value, self.encoding)
                    )
            elif isinstance(value, (tuple, list)):
                try:
                    return ''.join([chr(x) for x in value])
                except ValueError:
                    raise error.PyAsn1Error(
                        'Bad %s initializer \'%s\'' % (self.__class__.__name__, value)
                    )
            else:
                return str(value)
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def prettyIn(self, value):
            if isinstance(value, bytes):
                return value
            elif isinstance(value, str):
                try:
                    return value.encode(self.encoding)
                except UnicodeEncodeError:
                    raise error.PyAsn1Error(
                        'Can\'t encode string \'%s\' with \'%s\' codec' % (value, self.encoding)
                    )
            elif isinstance(value, OctetString):  # a shortcut, bytes() would work the same way
                return value.asOctets()
            elif isinstance(value, base.AbstractSimpleAsn1Item):  # this mostly targets Integer objects
                return self.prettyIn(str(value))
            elif isinstance(value, (tuple, list)):
                return self.prettyIn(bytes(value))
            else:
                return bytes(value)
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def prettyOut(self, value):
        if sys.version_info[0] <= 2:
            numbers = tuple((ord(x) for x in value))
        else:
            numbers = tuple(value)
        for x in numbers:
            if x < 32 or x > 126:
                return '0x' + ''.join(('%.2x' % x for x in numbers))
        else:
            try:
                return value.decode(self.encoding)

            except UnicodeDecodeError:
                raise error.PyAsn1Error(
                    "Can't decode string '%s' with '%s' codec at '%s'" % (value, self.encoding, self.__class__.__name__)
                )
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def __getitem__(self, idx):
        if octets.isStringType(idx):
            try:
                return self.getComponentByName(idx)

            except error.PyAsn1Error:
                # duck-typing dict
                raise KeyError(sys.exc_info()[1])

        else:
            try:
                return self.getComponentByPosition(idx)

            except error.PyAsn1Error:
                # duck-typing list
                raise IndexError(sys.exc_info()[1])
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def __setitem__(self, idx, value):
        if octets.isStringType(idx):
            try:
                self.setComponentByName(idx, value)

            except error.PyAsn1Error:
                # duck-typing dict
                raise KeyError(sys.exc_info()[1])

        else:
            try:
                self.setComponentByPosition(idx, value)

            except error.PyAsn1Error:
                # duck-typing list
                raise IndexError(sys.exc_info()[1])
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def getComponentByName(self, name):
        """Returns |ASN.1| type component by name.

        Equivalent to Python :class:`dict` subscription operation (e.g. `[]`).

        Parameters
        ----------
        name : :class:`str`
            |ASN.1| type component name

        Returns
        -------
        : :py:class:`~pyasn1.type.base.PyAsn1Item`
            Instantiate |ASN.1| component type or return existing component value
        """
        if self._componentTypeLen:
            idx = self.componentType.getPositionByName(name)
        else:
            try:
                idx = self._dynamicNames.getPositionByName(name)

            except KeyError:
                raise error.PyAsn1Error('Name %s not found' % (name,))

        return self.getComponentByPosition(idx)
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def _cloneComponentValues(self, myClone, cloneValueFlag):
        try:
            component = self.getComponent()
        except error.PyAsn1Error:
            pass
        else:
            if isinstance(component, Choice):
                tagSet = component.effectiveTagSet
            else:
                tagSet = component.tagSet
            if isinstance(component, base.AbstractConstructedAsn1Item):
                myClone.setComponentByType(
                    tagSet, component.clone(cloneValueFlag=cloneValueFlag)
                )
            else:
                myClone.setComponentByType(tagSet, component.clone())
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def getComponent(self, innerFlag=0):
        """Return currently assigned component of the |ASN.1| object.

        Returns
        -------
        : :py:class:`~pyasn1.type.base.PyAsn1Item`
            a PyASN1 object
        """
        if self._currentIdx is None:
            raise error.PyAsn1Error('Component not chosen')
        else:
            c = self._componentValues[self._currentIdx]
            if innerFlag and isinstance(c, Choice):
                return c.getComponent(innerFlag)
            else:
                return c
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def getName(self, innerFlag=False):
        """Return the name of currently assigned component of the |ASN.1| object.

        Returns
        -------
        : :py:class:`str`
            |ASN.1| component name
        """
        if self._currentIdx is None:
            raise error.PyAsn1Error('Component not chosen')
        else:
            if innerFlag:
                c = self._componentValues[self._currentIdx]
                if isinstance(c, Choice):
                    return c.getName(innerFlag)
            return self.componentType.getNameByPosition(self._currentIdx)
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def tagExplicitly(self, superTag):
        """Return explicitly tagged *TagSet*

        Create a new *TagSet* representing callee *TagSet* explicitly tagged
        with passed tag(s). With explicit tagging mode, new tags are appended
        to existing tag(s).

        Parameters
        ----------
        superTag: :class:`~pyasn1.type.tag.Tag`
            *Tag* object to tag this *TagSet*

        Returns
        -------
        : :class:`~pyasn1.type.tag.TagSet`
            New *TagSet* object
        """
        if superTag.tagClass == tagClassUniversal:
            raise error.PyAsn1Error("Can't tag with UNIVERSAL class tag")
        if superTag.tagFormat != tagFormatConstructed:
            superTag = Tag(superTag.tagClass, tagFormatConstructed, superTag.tagId)
        return self + superTag
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def prettyIn(self, value):
            try:
                if isinstance(value, unicode):
                    return value
                elif isinstance(value, str):
                    return value.decode(self.encoding)
                elif isinstance(value, (tuple, list)):
                    return self.prettyIn(''.join([chr(x) for x in value]))
                elif isinstance(value, univ.OctetString):
                    return value.asOctets().decode(self.encoding)
                else:
                    return unicode(value)

            except (UnicodeDecodeError, LookupError):
                raise error.PyAsn1Error(
                    "Can't decode string '%s' with codec %s" % (value, self.encoding)
                )
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def prettyIn(self, value):
            try:
                if isinstance(value, str):
                    return value
                elif isinstance(value, bytes):
                    return value.decode(self.encoding)
                elif isinstance(value, (tuple, list)):
                    return self.prettyIn(bytes(value))
                elif isinstance(value, univ.OctetString):
                    return value.asOctets().decode(self.encoding)
                else:
                    return str(value)

            except (UnicodeDecodeError, LookupError):
                raise error.PyAsn1Error(
                    "Can't decode string '%s' with codec %s" % (value, self.encoding)
                )
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def __new__(cls):
        if cls._instance is None:
            def getPlug(name):
                def plug(self, *args, **kw):
                    raise error.PyAsn1Error('Uninitialized ASN.1 value ("%s" attribute looked up)' % name)
                return plug

            op_names = [name
                        for typ in (str, int, list, dict)
                        for name in dir(typ)
                        if (name not in cls.skipMethods and
                            name.startswith('__') and
                            name.endswith('__') and
                            calling.callable(getattr(typ, name)))]

            for name in set(op_names):
                setattr(cls, name, getPlug(name))

            cls._instance = object.__new__(cls)

        return cls._instance
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def getTypeByPosition(self, idx):
        """Return ASN.1 type object by its position in fields set.

        Parameters
        ----------
        idx: :py:class:`int`
            Field index

        Returns
        -------
        :
            ASN.1 type

        Raises
        ------
        : :class:`~pyasn1.error.PyAsn1Error`
            If given position is out of fields range
        """
        try:
            return self.__namedTypes[idx].asn1Object

        except IndexError:
            raise error.PyAsn1Error('Type position out of range')
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def getPositionByType(self, tagSet):
        """Return field position by its ASN.1 type.

        Parameters
        ----------
        tagSet: :class:`~pysnmp.type.tag.TagSet`
            ASN.1 tag set distinguishing one ASN.1 type from others.

        Returns
        -------
        : :py:class:`int`
            ASN.1 type position in fields set

        Raises
        ------
        : :class:`~pyasn1.error.PyAsn1Error`
            If *tagSet* is not present or ASN.1 types are not unique within callee *NamedTypes*
        """
        try:
            return self.__tagToPosMap[tagSet]

        except KeyError:
            raise error.PyAsn1Error('Type %s not found' % (tagSet,))
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def getNameByPosition(self, idx):
        """Return field name by its position in fields set.

        Parameters
        ----------
        idx: :py:class:`idx`
            Field index

        Returns
        -------
        : :py:class:`str`
            Field name

        Raises
        ------
        : :class:`~pyasn1.error.PyAsn1Error`
            If given field name is not present in callee *NamedTypes*
        """
        try:
            return self.__namedTypes[idx].name

        except IndexError:
            raise error.PyAsn1Error('Type position out of range')
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def getPositionByName(self, name):
        """Return field position by filed name.

        Parameters
        ----------
        name: :py:class:`str`
            Field name

        Returns
        -------
        : :py:class:`int`
            Field position in fields set

        Raises
        ------
        : :class:`~pyasn1.error.PyAsn1Error`
            If *name* is not present or not unique within callee *NamedTypes*
        """
        try:
            return self.__nameToPosMap[name]

        except KeyError:
            raise error.PyAsn1Error('Name %s not found' % (name,))
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def valueDecoder(self, substrate, asn1Spec,
                     tagSet=None, length=None, state=None,
                     decodeFun=None, substrateFun=None,
                     **options):
        head, tail = substrate[:length], substrate[length:]
        if not head or length != 1:
            raise error.PyAsn1Error('Not single-octet Boolean payload')
        byte = oct2int(head[0])
        # CER/DER specifies encoding of TRUE as 0xFF and FALSE as 0x0, while
        # BER allows any non-zero value as TRUE; cf. sections 8.2.2. and 11.1 
        # in http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf
        if byte == 0xff:
            value = 1
        elif byte == 0x00:
            value = 0
        else:
            raise error.PyAsn1Error('Unexpected Boolean payload: %s' % byte)
        return self._createComponent(asn1Spec, tagSet, value), tail

# TODO: prohibit non-canonical encoding
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def indefLenValueDecoder(self, substrate, asn1Spec,
                             tagSet=None, length=None, state=None,
                             decodeFun=None, substrateFun=None,
                             **options):
        if substrateFun:
            return substrateFun(
                self._createComponent(asn1Spec, tagSet, ''),
                substrate, length
            )

        value, substrate = decodeFun(substrate, asn1Spec, tagSet, length, **options)

        eooMarker, substrate = decodeFun(substrate, allowEoo=True, **options)

        if eooMarker is eoo.endOfOctets:
            return value, substrate
        else:
            raise error.PyAsn1Error('Missing end-of-octets terminator')
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def valueDecoder(self, substrate, asn1Spec,
                     tagSet=None, length=None, state=None,
                     decodeFun=None, substrateFun=None,
                     **options):

        if tagSet[0].tagFormat != tag.tagFormatSimple:
            raise error.PyAsn1Error('Simple tag format expected')

        head, tail = substrate[:length], substrate[length:]

        if not head:
            return self._createComponent(asn1Spec, tagSet, 0), tail

        value = from_bytes(head, signed=True)

        return self._createComponent(asn1Spec, tagSet, value), tail
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def valueDecoder(self, substrate, asn1Spec,
                     tagSet=None, length=None, state=None,
                     decodeFun=None, substrateFun=None,
                     **options):

        if tagSet[0].tagFormat != tag.tagFormatSimple:
            raise error.PyAsn1Error('Simple tag format expected')

        head, tail = substrate[:length], substrate[length:]

        component = self._createComponent(asn1Spec, tagSet)

        if head:
            raise error.PyAsn1Error('Unexpected %d-octet substrate for Null' % length)

        return component, tail
项目:zeronet-debian    作者:bashrc    | 项目源码 | 文件源码
def prettyIn(self, value):
        if not isinstance(value, str):
            try:
                return int(value)
            except:
                raise error.PyAsn1Error(
                    'Can\'t coerce %s into integer: %s' % (value, sys.exc_info()[1])
                    )
        r = self.__namedValues.getValue(value)
        if r is not None:
            return r
        try:
            return int(value)
        except:
            raise error.PyAsn1Error(
                'Can\'t coerce %s into integer: %s' % (value, sys.exc_info()[1])
                )
项目:zeronet-debian    作者:bashrc    | 项目源码 | 文件源码
def prettyIn(self, value):
            if isinstance(value, bytes):
                return value
            elif isinstance(value, OctetString):
                return value.asOctets()
            elif isinstance(value, (tuple, list, map)):
                try:
                    return bytes(value)
                except ValueError:
                    raise error.PyAsn1Error(
                        'Bad OctetString initializer \'%s\'' % (value,)
                        )
            else:
                try:
                    return str(value).encode(self._encoding)
                except UnicodeEncodeError:
                    raise error.PyAsn1Error(
                        'Can\'t encode string \'%s\' with \'%s\' codec' % (value, self._encoding)
                        )
项目:zeronet-debian    作者:bashrc    | 项目源码 | 文件源码
def fromBinaryString(self, value):
        bitNo = 8; byte = 0; r = ()
        for v in value:
            if bitNo:
                bitNo = bitNo - 1
            else:
                bitNo = 7
                r = r + (byte,)
                byte = 0
            if v == '0':
                v = 0
            elif v == '1':
                v = 1
            else:
                raise error.PyAsn1Error(
                    'Non-binary OCTET STRING initializer %s' % (v,)
                    )
            byte = byte | (v << bitNo)
        return octets.ints2octs(r + (byte,))
项目:zeronet-debian    作者:bashrc    | 项目源码 | 文件源码
def _cloneComponentValues(self, myClone, cloneValueFlag):
        try:
            c = self.getComponent()
        except error.PyAsn1Error:
            pass
        else:
            if isinstance(c, Choice):
                tagSet = c.getEffectiveTagSet()
            else:
                tagSet = c.getTagSet()
            if isinstance(c, base.AbstractConstructedAsn1Item):
                myClone.setComponentByType(
                    tagSet, c.clone(cloneValueFlag=cloneValueFlag)
                    )
            else:
                myClone.setComponentByType(tagSet, c.clone())
项目:zeronet-debian    作者:bashrc    | 项目源码 | 文件源码
def clone(self, parentType, tagMap, uniq=False):
        if self.__defType is not None and tagMap.getDef() is not None:
            raise error.PyAsn1Error('Duplicate default value at %s' % (self,))
        if tagMap.getDef() is not None:
            defType = tagMap.getDef()
        else:
            defType = self.__defType

        posMap = self.__posMap.copy()
        for k in tagMap.getPosMap():
            if uniq and k in posMap:
                raise error.PyAsn1Error('Duplicate positive key %s' % (k,))
            posMap[k] = parentType

        negMap = self.__negMap.copy()
        negMap.update(tagMap.getNegMap())

        return self.__class__(
            posMap, negMap, defType,
            )
项目:zeronet-debian    作者:bashrc    | 项目源码 | 文件源码
def __init__(self, *namedValues):
        self.nameToValIdx = {}; self.valToNameIdx = {}
        self.namedValues = ()        
        automaticVal = 1
        for namedValue in namedValues:
            if isinstance(namedValue, tuple):
                name, val = namedValue
            else:
                name = namedValue
                val = automaticVal
            if name in self.nameToValIdx:
                raise error.PyAsn1Error('Duplicate name %s' % (name,))
            self.nameToValIdx[name] = val
            if val in self.valToNameIdx:
                raise error.PyAsn1Error('Duplicate value %s=%s' % (name, val))
            self.valToNameIdx[val] = name
            self.namedValues = self.namedValues + ((name, val),)
            automaticVal = automaticVal + 1
项目:zeronet-debian    作者:bashrc    | 项目源码 | 文件源码
def indefLenValueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet,
                     length, state, decodeFun, substrateFun):
        r = self._createComponent(asn1Spec, tagSet)
        if substrateFun:
            return substrateFun(r, substrate, length)
        if r.getTagSet() == tagSet: # explicitly tagged Choice
            component, substrate = decodeFun(substrate, r.getComponentTagMap())
            eooMarker, substrate = decodeFun(substrate)  # eat up EOO marker
            if not eoo.endOfOctets.isSameTypeWith(eooMarker) or \
                    eooMarker != eoo.endOfOctets:
                raise error.PyAsn1Error('No EOO seen before substrate ends')
        else:
            component, substrate= decodeFun(
                substrate, r.getComponentTagMap(), tagSet, length, state
            )
        if isinstance(component, univ.Choice):
            effectiveTagSet = component.getEffectiveTagSet()
        else:
            effectiveTagSet = component.getTagSet()
        r.setComponentByType(effectiveTagSet, component, 0, asn1Spec is None)
        return r, substrate
项目:plugin.video.bdyun    作者:caasiu    | 项目源码 | 文件源码
def prettyIn(self, value):
        if not isinstance(value, str):
            try:
                return int(value)
            except:
                raise error.PyAsn1Error(
                    'Can\'t coerce %r into integer: %s' % (value, sys.exc_info()[1])
                    )
        r = self.__namedValues.getValue(value)
        if r is not None:
            return r
        try:
            return int(value)
        except:
            raise error.PyAsn1Error(
                'Can\'t coerce %r into integer: %s' % (value, sys.exc_info()[1])
                )
项目:plugin.video.bdyun    作者:caasiu    | 项目源码 | 文件源码
def prettyIn(self, value):
            if isinstance(value, str):
                return value
            elif isinstance(value, unicode):
                try:
                    return value.encode(self._encoding)
                except (LookupError, UnicodeEncodeError):
                    raise error.PyAsn1Error(
                        'Can\'t encode string \'%s\' with \'%s\' codec' % (value, self._encoding)
                    )
            elif isinstance(value, (tuple, list)):
                try:
                    return ''.join([ chr(x) for x in value ])
                except ValueError:
                    raise error.PyAsn1Error(
                        'Bad OctetString initializer \'%s\'' % (value,)
                    )                
            else:
                return str(value)
项目:plugin.video.bdyun    作者:caasiu    | 项目源码 | 文件源码
def fromBinaryString(self, value):
        bitNo = 8; byte = 0; r = ()
        for v in value:
            if bitNo:
                bitNo = bitNo - 1
            else:
                bitNo = 7
                r = r + (byte,)
                byte = 0
            if v == '0':
                v = 0
            elif v == '1':
                v = 1
            else:
                raise error.PyAsn1Error(
                    'Non-binary OCTET STRING initializer %s' % (v,)
                    )
            byte = byte | (v << bitNo)
        return octets.ints2octs(r + (byte,))
项目:plugin.video.bdyun    作者:caasiu    | 项目源码 | 文件源码
def _cloneComponentValues(self, myClone, cloneValueFlag):
        try:
            c = self.getComponent()
        except error.PyAsn1Error:
            pass
        else:
            if isinstance(c, Choice):
                tagSet = c.getEffectiveTagSet()
            else:
                tagSet = c.getTagSet()
            if isinstance(c, base.AbstractConstructedAsn1Item):
                myClone.setComponentByType(
                    tagSet, c.clone(cloneValueFlag=cloneValueFlag)
                    )
            else:
                myClone.setComponentByType(tagSet, c.clone())
项目:oscars2016    作者:0x0ece    | 项目源码 | 文件源码
def prettyIn(self, value):
            if isinstance(value, bytes):
                return value
            elif isinstance(value, str):
                try:
                    return value.encode(self._encoding)
                except UnicodeEncodeError:
                    raise error.PyAsn1Error(
                        'Can\'t encode string \'%s\' with \'%s\' codec' % (value, self._encoding)
                    )
            elif isinstance(value, OctetString):
                return value.asOctets()
            elif isinstance(value, (tuple, list, map)):
                try:
                    return bytes(value)
                except ValueError:
                    raise error.PyAsn1Error(
                        'Bad OctetString initializer \'%s\'' % (value,)
                    )
            else:
                try:
                    return str(value).encode(self._encoding)
                except UnicodeEncodeError:
                    raise error.PyAsn1Error(
                        'Can\'t encode string \'%s\' with \'%s\' codec' % (value, self._encoding)
                    )