Python pyasn1.error.PyAsn1Error() Examples

The following are 30 code examples of pyasn1.error.PyAsn1Error(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyasn1.error , or try the search function .
Example #1
Source File: univ.py    From oss-ftp with MIT License 6 votes vote down vote up
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])
                ) 
Example #2
Source File: univ.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def prettyIn(self, value):
        if not octets.isStringType(value):
            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])
            ) 
Example #3
Source File: univ.py    From oss-ftp with MIT License 6 votes vote down vote up
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()) 
Example #4
Source File: tagmap.py    From oss-ftp with MIT License 6 votes vote down vote up
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,
            ) 
Example #5
Source File: decoder.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #6
Source File: univ.py    From oss-ftp with MIT License 6 votes vote down vote up
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) 
Example #7
Source File: univ.py    From oss-ftp with MIT License 6 votes vote down vote up
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,)) 
Example #8
Source File: decoder.py    From oss-ftp with MIT License 6 votes vote down vote up
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 
Example #9
Source File: base.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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 callable(getattr(typ, name))]

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

            cls._instance = object.__new__(cls)

        return cls._instance 
Example #10
Source File: decoder.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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

# TODO: prohibit non-canonical encoding 
Example #11
Source File: decoder.py    From oss-ftp with MIT License 6 votes vote down vote up
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 
Example #12
Source File: namedval.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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 += 1 
Example #13
Source File: namedtype.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def getPositionNearType(self, tagSet, idx):
        if not self.__ambigiousTypes:
            self.__buildAmbigiousTagMap()
        try:
            return idx + self.__ambigiousTypes[idx].getPositionByType(tagSet)
        except KeyError:
            raise error.PyAsn1Error('Type position out of range') 
Example #14
Source File: encoder.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
        raise error.PyAsn1Error('Not implemented') 
Example #15
Source File: base.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def setComponentByPosition(self, idx, value, verifyConstraints=True):
        raise error.PyAsn1Error('Method not implemented') 
Example #16
Source File: decoder.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length,
                     state, decodeFun, substrateFun):
        head, tail = substrate[:length], substrate[length:]
        if tagSet[0][1] == tag.tagFormatSimple:  # XXX what tag to check?
            return self._createComponent(asn1Spec, tagSet, head), tail
        if not self.supportConstructedForm:
            raise error.PyAsn1Error('Constructed encoding form prohibited at %s' % self.__class__.__name__)
        r = self._createComponent(asn1Spec, tagSet, '')
        if substrateFun:
            return substrateFun(r, substrate, length)
        while head:
            component, head = decodeFun(head, self.protoComponent)
            r = r + component
        return r, tail 
Example #17
Source File: base.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _verifySubtypeSpec(self, value, idx=None):
        try:
            self._subtypeSpec(value, idx)
        except error.PyAsn1Error:
            c, i, t = sys.exc_info()
            raise c('%s at %s' % (i, self.__class__.__name__)) 
Example #18
Source File: base.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def __getattr__(self, attr):
        if attr in self.skipMethods:
            raise AttributeError('attribute %s not present' % attr)
        raise error.PyAsn1Error('No value for "%s"' % attr) 
Example #19
Source File: base.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def getComponentByPosition(self, idx):
        raise error.PyAsn1Error('Method not implemented') 
Example #20
Source File: tag.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def tagExplicitly(self, superTag):
        tagClass, tagFormat, tagId = superTag
        if tagClass == tagClassUniversal:
            raise error.PyAsn1Error(
                'Can\'t tag with UNIVERSAL-class tag'
            )
        if tagFormat != tagFormatConstructed:
            superTag = Tag(tagClass, tagFormatConstructed, tagId)
        return self + superTag 
Example #21
Source File: decoder.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _getComponentTagMap(self, r, idx):
        try:
            return r.getComponentTagMapNearPosition(idx)
        except error.PyAsn1Error:
            return 
Example #22
Source File: decoder.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet,
                     length, state, decodeFun, substrateFun):
        head, tail = substrate[:length], substrate[length:]
        r = self._createComponent(asn1Spec, tagSet)
        if head:
            raise error.PyAsn1Error('Unexpected %d-octet substrate for Null' % length)
        return r, tail 
Example #23
Source File: encoder.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def __call__(self, client, defMode=False, maxChunkSize=0):
        return encoder.Encoder.__call__(self, client, defMode, maxChunkSize)


#: Turns ASN.1 object into CER octet stream.
#:
#: Takes any ASN.1 object (e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative)
#: walks all its components recursively and produces a CER octet stream.
#:
#: Parameters
#: ----------
#  value: any pyasn1 object (e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative)
#:     A pyasn1 object to encode
#:
#: defMode: :py:class:`bool`
#:     If `False`, produces indefinite length encoding
#:
#: maxChunkSize: :py:class:`int`
#:     Maximum chunk size in chunked encoding mode (0 denotes unlimited chunk size)
#:
#: Returns
#: -------
#: : :py:class:`bytes` (Python 3) or :py:class:`str` (Python 2)
#:     Given ASN.1 object encoded into BER octetstream
#:
#: Raises
#: ------
#: : :py:class:`pyasn1.error.PyAsn1Error`
#:     On encoding errors 
Example #24
Source File: decoder.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def indefLenValueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet,
                             length, state, decodeFun, substrateFun):
        if substrateFun:
            return substrateFun(
                self._createComponent(asn1Spec, tagSet, ''),
                substrate, length
            )
        value, substrate = decodeFun(substrate, asn1Spec, tagSet, length)
        terminator, substrate = decodeFun(substrate, allowEoo=True)
        if eoo.endOfOctets.isSameTypeWith(terminator) and \
                terminator == eoo.endOfOctets:
            return value, substrate
        else:
            raise error.PyAsn1Error('Missing end-of-octets terminator') 
Example #25
Source File: decoder.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _createComponent(self, asn1Spec, tagSet, value=None):
        if tagSet[0][1] not in self.tagFormats:
            raise error.PyAsn1Error('Invalid tag format %s for %s' % (tagSet[0], self.protoComponent.prettyPrintType()))
        if asn1Spec is None:
            return self.protoComponent.clone(tagSet)
        else:
            return asn1Spec.clone() 
Example #26
Source File: decoder.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _createComponent(self, asn1Spec, tagSet, value=None):
        if tagSet[0][1] not in self.tagFormats:
            raise error.PyAsn1Error('Invalid tag format %s for %s' % (tagSet[0], self.protoComponent.prettyPrintType()))
        if asn1Spec is None:
            return self.protoComponent.clone(value, tagSet)
        elif value is None:
            return asn1Spec
        else:
            return asn1Spec.clone(value) 
Example #27
Source File: decoder.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def indefLenValueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet,
                             length, state, decodeFun, substrateFun):
        raise error.PyAsn1Error('Indefinite length mode decoder not implemented for %s' % (tagSet,)) 
Example #28
Source File: decoder.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet,
                     length, state, decodeFun, substrateFun):
        raise error.PyAsn1Error('Decoder not implemented for %s' % (tagSet,)) 
Example #29
Source File: utils.py    From oss-ftp with MIT License 5 votes vote down vote up
def decode_dss_signature(signature):
    try:
        data, remaining = decoder.decode(signature, asn1Spec=_DSSSigValue())
    except PyAsn1Error:
        raise ValueError("Invalid signature data. Unable to decode ASN.1")

    if remaining:
        raise ValueError(
            "The signature contains bytes after the end of the ASN.1 sequence."
        )

    r = int(data.getComponentByName('r'))
    s = int(data.getComponentByName('s'))
    return (r, s) 
Example #30
Source File: tagmap.py    From oss-ftp with MIT License 5 votes vote down vote up
def __getitem__(self, tagSet):
        if tagSet in self.__posMap:
            return self.__posMap[tagSet]
        elif tagSet in self.__negMap:
            raise error.PyAsn1Error('Key in negative map')
        elif self.__defType is not None:
            return self.__defType
        else:
            raise KeyError()