• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python TypeConverter.TypeConverter类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中netzob.Common.Models.Types.TypeConverter.TypeConverter的典型用法代码示例。如果您正苦于以下问题:Python TypeConverter类的具体用法?Python TypeConverter怎么用?Python TypeConverter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了TypeConverter类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _deserializeAlignment

    def _deserializeAlignment(self, regex, mask, unitSize=AbstractType.UNITSIZE_8):
        """
        deserializeAlignment: Transforms the C extension results
        in a python readable way
        @param regex the C returned regex
        @param mask the C returned mask
        @param unitSize the unitSize
        @returns the python alignment
        """
        if not (unitSize == AbstractType.UNITSIZE_8 or unitSize == AbstractType.UNITSIZE_4):
            raise ValueError("Deserializing with unitSize {0} not yet implemented, only 4 and 8 supported.".format(unitSize))

        align = ""
        for i, c in enumerate(mask):
            if c != '\x02':
                if c == '\x01':
                    if unitSize == AbstractType.UNITSIZE_8:
                        align += "--"
                    elif unitSize == AbstractType.UNITSIZE_4:
                        align += "-"
                else:
                    if unitSize == AbstractType.UNITSIZE_8:
                        align += TypeConverter.convert(regex[i:i + 1], Raw, HexaString)
                    elif unitSize == AbstractType.UNITSIZE_4:
                        align += TypeConverter.convert(regex[i:i + 1], Raw, HexaString)[1:]
        return align
开发者ID:RepublicMaster,项目名称:netzob,代码行数:26,代码来源:FieldSplitAligned.py


示例2: _computeExpectedValue

    def _computeExpectedValue(self, parsingPath):
        self._logger.debug("compute expected value for Internet checksum field")
                
        # first checks the pointed fields all have a value
        hasValue = True
        for field in self.fieldDependencies:
            if field.domain != self and not parsingPath.isDataAvailableForVariable(field.domain):
                self._logger.debug("Field : {0} has no value".format(field.id))
                hasValue = False

        if not hasValue:
            raise Exception("Expected value cannot be computed, some dependencies are missing for domain {0}".format(self))
        else:
            fieldValues = []
            for field in self.fieldDependencies:
                if field.domain is self:
                    fieldSize = random.randint(field.domain.dataType.size[0], field.domain.dataType.size[1])
                    fieldValue = "\x00"* (fieldSize / 8)
                else:
                    fieldValue = TypeConverter.convert(parsingPath.getDataAssignedToVariable(field.domain), BitArray, Raw)
                if fieldValue is None:
                    break
                else:
                    fieldValues.append(fieldValue)

            fieldValues = ''.join(fieldValues)
            # compute the checksum of this value
            chsum = self.__checksum(fieldValues)
            b = TypeConverter.convert(chsum, Integer, BitArray, src_unitSize=AbstractType.UNITSIZE_16, src_sign = AbstractType.SIGN_UNSIGNED)
            return b
开发者ID:chubbymaggie,项目名称:netzob,代码行数:30,代码来源:InternetChecksum.py


示例3: mutate

    def mutate(self, prefixDescription=None):
        """Generate various mutations of the current ASCII value.

        Mutations are first applied on the ASCII value than, each obtained mutations generates
        new bitarray mutations.
        ASCII mutations are:

        * Original Version
        * Original Version in Upper case
        * Original Version in Lower case

        >>> from netzob.all import *
        >>> t = ASCII("helloworld")
        >>> print t.mutate()
        {'ascii(inversed)-bits(littleEndian)': bitarray('00100110001101100100111011110110111011101111011000110110001101101010011000010110'), 'ascii(inversed-upper)-bits(littleEndian)': bitarray('00100010001100100100101011110010111010101111001000110010001100101010001000010010'), 'ascii(upper)-bits(littleEndian)': bitarray('00010010101000100011001000110010111100101110101011110010010010100011001000100010'), 'ascii-bits(bigEndian)': bitarray('01101000011001010110110001101100011011110111011101101111011100100110110001100100'), 'ascii(inversed)-bits(bigEndian)': bitarray('01100100011011000111001001101111011101110110111101101100011011000110010101101000'), 'ascii(upper)-bits(bigEndian)': bitarray('01001000010001010100110001001100010011110101011101001111010100100100110001000100'), 'ascii-bits(littleEndian)': bitarray('00010110101001100011011000110110111101101110111011110110010011100011011000100110'), 'ascii(inversed-upper)-bits(bigEndian)': bitarray('01000100010011000101001001001111010101110100111101001100010011000100010101001000')}


        :keyword prefixDescription: prefix to attach to the description of the generated mutation.
        :type prefixDescription: :class:`str`
        :return: a dict of computed mutations having the same types than the initial one.
        :rtype: :class:`dict`<str>=:class:`netzob.Common.Models.Types.AbstractType.AbstractType`
        """
        if prefixDescription is None:
            prefixDescription = ""
        else:
            prefixDescription += "-"

        from netzob.Common.Models.Types.TypeConverter import TypeConverter
        from netzob.Common.Models.Types.BitArray import BitArray

        if self.value is None:
            val = self.generate()
        else:
            val = self.value

        strValue = TypeConverter.convert(val, BitArray, ASCII)

        mutations = dict()

        mutations["{0}ascii".format(prefixDescription)] = strValue
        mutations["{0}ascii(inversed)".format(prefixDescription)] = strValue[::-1]
        if strValue != strValue.upper():
            mutations["{0}ascii(upper)".format(prefixDescription)] = strValue.upper()
            mutations["{0}ascii(inversed-upper)".format(prefixDescription)] = strValue[::-1].upper()
        if strValue != strValue.lower():
            mutations["{0}ascii(lower)".format(prefixDescription)] = strValue.lower()
            mutations["{0}ascii(inversed-lower)".format(prefixDescription)] = strValue[::-1].lower()

        results = dict()
        for mutationName, mutationValue in mutations.iteritems():
            ba = BitArray(TypeConverter.convert(mutationValue, ASCII, BitArray))
            results.update(ba.mutate(mutationName))

        return results
开发者ID:chubbymaggie,项目名称:netzob,代码行数:54,代码来源:ASCII.py


示例4: __repr__

 def __repr__(self):
     if self.value is not None:
         from netzob.Common.Models.Types.TypeConverter import TypeConverter
         from netzob.Common.Models.Types.BitArray import BitArray
         return str(TypeConverter.convert(self.value, BitArray, self.__class__))
     else:
         return str(self.value)
开发者ID:chubbymaggie,项目名称:netzob,代码行数:7,代码来源:Raw.py


示例5: __init__

    def __init__(self, value=None, size=(None, None)):
        if value is not None and not isinstance(value, bitarray):
            from netzob.Common.Models.Types.TypeConverter import TypeConverter
            from netzob.Common.Models.Types.BitArray import BitArray
            value = TypeConverter.convert(value, HexaString, BitArray)

        super(HexaString, self).__init__(self.__class__.__name__, value, size)
开发者ID:chubbymaggie,项目名称:netzob,代码行数:7,代码来源:HexaString.py


示例6: specialize

    def specialize(self, memory=None, generationStrategy=None):
        """Specialize and generate an hexastring which content
        follows the fields definitions attached to the field of the symbol.

        >>> from netzob.all import *
        >>> f1 = Field(domain=ASCII(nbChars=5))
        >>> f0 = Field(domain=Size(f1))
        >>> s = Symbol(fields=[f0, f1])
        >>> result = s.specialize()
        >>> print result[0]
        \x05
        >>> print len(result)
        6

        :keyword generationStrategy: if set, the strategy will be used to generate the fields definitions
        :type generaionrStrategy: :class:``

        :return: a generated content represented as a Raw
        :rtype: :class:`str``
        :raises: :class:`netzob.Common.Models.Vocabulary.AbstractField.GenerationException` if an error occurs while generating a message
        """
        from netzob.Common.Models.Vocabulary.Domain.Specializer.MessageSpecializer import MessageSpecializer
        msg = MessageSpecializer(memory=memory)
        spePath = msg.specializeSymbol(self)

        if spePath is not None:
            return TypeConverter.convert(spePath.generatedContent, BitArray, Raw)
开发者ID:RepublicMaster,项目名称:netzob,代码行数:27,代码来源:Symbol.py


示例7: writeSymbol

    def writeSymbol(self, symbol):
        """Write the specified symbol on the communication channel
        after specializing it into a contextualized message.

        :param symbol: the symbol to write on the channel
        :type symbol: :class:`netzob.Common.Models.Vocabulary.Symbol.Symbol`
        :raise TypeError if parameter is not valid and Exception if an exception occurs.
        """
        if symbol is None:
            raise TypeError("The symbol to write on the channel cannot be None")

        self._logger.info("Going to specialize symbol: '{0}' (id={1}).".format(symbol.name, symbol.id))
        
        dataBin = self.specializer.specializeSymbol(symbol).generatedContent

        self.memory = self.specializer.memory
        self.parser.memory = self.memory
        data = TypeConverter.convert(dataBin, BitArray, Raw)
        symbol.messages.append(RawMessage(data))

        self._logger.info("Data generated from symbol '{0}':\n{1}.".format(symbol.name, symbol))
        
        self._logger.info("Going to write to communication channel...")
        self.channel.write(data)
        self._logger.info("Writing to commnunication channel donne..")
开发者ID:chubbymaggie,项目名称:netzob,代码行数:25,代码来源:AbstractionLayer.py


示例8: generate

    def generate(self, generationStrategy=None):
        """Generates a random ASCII that respects the requested size.

        >>> from netzob.all import *
        >>> a = ASCII(nbChars=10)
        >>> gen = a.generate()
        >>> len(gen)/8
        10

        >>> b = ASCII("netzob")
        >>> gen = b.generate()
        >>> print len(gen)>0
        True

        """
        from netzob.Common.Models.Types.TypeConverter import TypeConverter
        from netzob.Common.Models.Types.BitArray import BitArray

        minSize, maxSize = self.nbChars
        if maxSize is None:
            maxSize = AbstractType.MAXIMUM_GENERATED_DATA_SIZE
        if minSize is None:
            minSize = 0

        generatedSize = random.randint(minSize, maxSize)
        randomContent = ''.join([random.choice(string.letters + string.digits) for i in xrange(generatedSize)])
        return TypeConverter.convert(randomContent, ASCII, BitArray)
开发者ID:chubbymaggie,项目名称:netzob,代码行数:27,代码来源:ASCII.py


示例9: generate

    def generate(self, generationStrategy=None):
        """Generates a random Raw that respects the requested size.

        >>> from netzob.all import *
        >>> a = Raw(nbBytes=(10))
        >>> gen = a.generate()
        >>> print len(gen)
        80

        >>> from netzob.all import *
        >>> a = Raw(nbBytes=(10, 20))
        >>> gen = a.generate()
        >>> print 10<=len(gen) and 20<=len(gen)
        True



        """
        from netzob.Common.Models.Types.TypeConverter import TypeConverter
        from netzob.Common.Models.Types.BitArray import BitArray

        minSize, maxSize = self.size
        if maxSize is None:
            maxSize = AbstractType.MAXIMUM_GENERATED_DATA_SIZE
        if minSize is None:
            minSize = 0

        generatedSize = random.randint(minSize, maxSize)
        return TypeConverter.convert(os.urandom(generatedSize / 8), Raw, BitArray)
开发者ID:chubbymaggie,项目名称:netzob,代码行数:29,代码来源:Raw.py


示例10: __str__

 def __str__(self):
     from netzob.Common.Models.Types.TypeConverter import TypeConverter
     from netzob.Common.Models.Types.BitArray import BitArray
     if self.value is not None:
         return "{0}={1} ({2})".format(self.typeName, TypeConverter.convert(self.value, BitArray, self.__class__), self.size)
     else:
         return "{0}={1} ({2})".format(self.typeName, self.value, self.size)
开发者ID:EastL,项目名称:netzob,代码行数:7,代码来源:AbstractType.py


示例11: _computeExpectedValue

    def _computeExpectedValue(self, parsingPath):
        self._logger.debug("compute expected value for Size field")
                
        # first checks the pointed fields all have a value
        hasValue = True
        for field in self.fieldDependencies:
            if field.domain != self and not parsingPath.isDataAvailableForVariable(field.domain):
                self._logger.debug("Field : {0} has no value".format(field.id))
                hasValue = False

        if not hasValue:
            raise Exception("Expected value cannot be computed, some dependencies are missing for domain {0}".format(self))
        else:
            size = 0
            for field in self.fieldDependencies:
                if field.domain is self:
                    fieldValue = self.dataType.generate()
                else:
                    fieldValue = parsingPath.getDataAssignedToVariable(field.domain)
                if fieldValue is None:
                    break
                else:
                    tmpLen = len(fieldValue)
                    size += tmpLen

            size = int(size * self.factor + self.offset)
            b = TypeConverter.convert(size, Decimal, BitArray)
            
#            while len(b)<self.dataType.size[0]:
#                b.insert(0, False)
        return b
开发者ID:RepublicMaster,项目名称:netzob,代码行数:31,代码来源:Size.py


示例12: specializeSymbol

    def specializeSymbol(self, symbol):
        """This method generates a message based on the provided symbol definition."""
        if symbol is None:
            raise Exception("Specified symbol is None")

        self._logger.debug("Specifies symbol '{0}'.".format(symbol.name))

        # this variable host all the specialization path
        specializingPaths = [SpecializingPath(memory=self.memory)]

        for field in symbol.fields:
            self._logger.debug("Specializing field {0}".format(field.name))

            fieldDomain = field.domain
            if fieldDomain is None:
                raise Exception("Cannot specialize field '{0}' since it defines no domain".format(fieldDomain))
        
            fs = FieldSpecializer(field, presets = self.presets)

            newSpecializingPaths = []
            for specializingPath in specializingPaths:
                newSpecializingPaths.extend(fs.specialize(specializingPath))

            specializingPaths = newSpecializingPaths

        if len(specializingPaths) > 1:
            self._logger.info("TODO: multiple valid paths found when specializing this message.")

        if len(specializingPaths) == 0:
            raise Exception("Cannot specialize this symbol.")

        retainedPath = specializingPaths[0]

        generatedContent = None
        # let's configure the generated content
        for field in symbol.fields:
            # TODO: only support one level of children... must be improved
            if len(field.fields) > 0:
                d = None
                for child in field.fields:
                    if d is None:
                        d = retainedPath.getDataAssignedToVariable(child.domain).copy()
                    else:
                        d += retainedPath.getDataAssignedToVariable(child.domain).copy()
                
            else:
                d = retainedPath.getDataAssignedToVariable(field.domain)
                
            if generatedContent is None:
                generatedContent = d.copy()
            else:
                generatedContent += d.copy()

        retainedPath.generatedContent = generatedContent

        self._logger.debug("Specialized message: {0}".format(TypeConverter.convert(retainedPath.generatedContent, BitArray, ASCII)))
        self.memory = retainedPath.memory

        return retainedPath
开发者ID:chubbymaggie,项目名称:netzob,代码行数:59,代码来源:MessageSpecializer.py


示例13: __str__

 def __str__(self):
     if self.value is not None:
         from netzob.Common.Models.Types.TypeConverter import TypeConverter
         from netzob.Common.Models.Types.BitArray import BitArray
         from netzob.Common.Models.Types.HexaString import HexaString
         return "{0}={1} ({2})".format(self.typeName, repr(TypeConverter.convert(self.value, BitArray, Raw)), self.size)
     else:
         return "{0}={1} ({2})".format(self.typeName, self.value, self.size)
开发者ID:chubbymaggie,项目名称:netzob,代码行数:8,代码来源:Raw.py


示例14: _generateDataValues

 def _generateDataValues(self, cellsData):
     result = []
     for data in cellsData:
         if len(data) > 0:
             result.append(TypeConverter.convert(data[:8], Raw, Decimal))  # We take only the first 8 octets
         else:
             result.append(0)
     return result
开发者ID:RepublicMaster,项目名称:netzob,代码行数:8,代码来源:CorrelationFinder.py


示例15: encode

    def encode(data, unitSize=AbstractType.UNITSIZE_32, endianness=AbstractType.defaultEndianness(), sign=AbstractType.SIGN_UNSIGNED):
        from netzob.Common.Models.Types.Raw import Raw
        from netzob.Common.Models.Types.TypeConverter import TypeConverter
        from netzob.Common.Models.Types.Integer import Integer

        intValue = TypeConverter.convert(data, Raw, Integer, dst_unitSize=AbstractType.UNITSIZE_32, dst_sign=AbstractType.SIGN_UNSIGNED)
        parsedTimestamp = datetime.fromtimestamp(intValue)

        return parsedTimestamp.strftime("%c")        
开发者ID:chubbymaggie,项目名称:netzob,代码行数:9,代码来源:Timestamp.py


示例16: __init__

    def __init__(self, value=None, nbBytes=None, unitSize=AbstractType.defaultUnitSize(), endianness=AbstractType.defaultEndianness(), sign=AbstractType.defaultSign()):
        if value is not None and not isinstance(value, bitarray):
            from netzob.Common.Models.Types.TypeConverter import TypeConverter
            from netzob.Common.Models.Types.BitArray import BitArray
            value = TypeConverter.convert(value, Raw, BitArray)

        nbBits = self._convertNbBytesinNbBits(nbBytes)

        super(Raw, self).__init__(self.__class__.__name__, value, nbBits, unitSize=unitSize, endianness=endianness, sign=sign)
开发者ID:chubbymaggie,项目名称:netzob,代码行数:9,代码来源:Raw.py


示例17: __init__

    def __init__(self, value=None, nbChars=(None, None), unitSize=AbstractType.defaultUnitSize(), endianness=AbstractType.defaultEndianness(), sign=AbstractType.defaultSign()):
        if value is not None and not isinstance(value, bitarray):
            from netzob.Common.Models.Types.TypeConverter import TypeConverter
            from netzob.Common.Models.Types.BitArray import BitArray
            value = TypeConverter.convert(value, ASCII, BitArray, src_unitSize=unitSize, src_endianness=endianness, src_sign=sign, dst_unitSize=unitSize, dst_endianness=endianness, dst_sign=sign)
        else:
            value = None

        self.nbChars = nbChars
        nbBits = self._convertNbCharsInNbBits(self.nbChars)

        super(ASCII, self).__init__(self.__class__.__name__, value, nbBits, unitSize=unitSize, endianness=endianness, sign=sign)
开发者ID:chubbymaggie,项目名称:netzob,代码行数:12,代码来源:ASCII.py


示例18: _sizeRelation

    def _sizeRelation(self, x, x_attribute, y, y_attribute):
        if x_attribute == self.ATTR_SIZE:
            if len(x) > 0:
                x = len(x)
        else:
            if len(x) > 0:
                x = TypeConverter.convert(x[:8], Raw, Integer)
            else:
                x = 0
        if y_attribute == self.ATTR_SIZE:
            if len(y) > 0:
                y = len(y)
        else:
            if len(y) > 0:
                y = TypeConverter.convert(y[:8], Raw, Integer)
            else:
                y = 0

        if x == y:
            return True
        else:
            return False
开发者ID:chubbymaggie,项目名称:netzob,代码行数:22,代码来源:RelationFinder.py


示例19: canParse

    def canParse(self, data, unitSize=AbstractType.defaultUnitSize(), endianness=AbstractType.defaultEndianness(), sign=AbstractType.defaultSign()):
        """Computes if specified data can be parsed as a Timestamp with the predefined constraints.

        >>> from netzob.all import *
        >>> time = Timestamp()
        >>> time.canParse(TypeConverter.convert(1444494130, Integer, BitArray, src_unitSize=AbstractType.UNITSIZE_32))
        True
        >>> # A timestamp is nothing else than 32bits parsed as an unsigned long
        >>> time.canParse(TypeConverter.convert("test", ASCII, BitArray))
        True
        >>> time.canParse(TypeConverter.convert("te", ASCII, BitArray))
        False
        
        However, some constrains over the definition of the Timestamp can be set to restrain the accepted values

        >>> from netzob.all import *
        >>> time = Timestamp(epoch=Timestamp.EPOCH_WINDOWS, unity=Timestamp.UNITY_NANOSECOND, unitSize = AbstractType.UNITSIZE_64)
        >>> # the returned year is < 1900
        >>> time.canParse(TypeConverter.convert("test", ASCII, BitArray))
        False

        """

        if data is None:
            raise TypeError("data cannot be None")
         
        # Timestamp must be 8 bits modulo length
        if len(data) % 8 != 0:
            return False

        if len(data) < int(self.unitSize):
            return False

        try:

            value = TypeConverter.convert(data[:int(self.unitSize)], BitArray, Integer, dst_unitSize=AbstractType.UNITSIZE_32, dst_sign=AbstractType.SIGN_UNSIGNED)

            # convert the value in seconds
            value = value / self.unity

            # add the utc now with the epoch
            timestamp_datetime = self.epoch + timedelta(seconds=value)
            
            # convert obtained datetime to timestamp in seconds 
            result_sec = int( timestamp_datetime.strftime('%s') )
            
            datetime.fromtimestamp(result_sec)
        except Exception:
            return False
        
        return True
开发者ID:chubbymaggie,项目名称:netzob,代码行数:51,代码来源:Timestamp.py


示例20: _computeExpectedValue

    def _computeExpectedValue(self, parsingPath):
        self._logger.debug("compute expected value for Size field")
                
        # first checks the pointed fields all have a value
        hasValue = True
        for field in self.fieldDependencies:
            if field.domain != self and not parsingPath.isDataAvailableForVariable(field.domain):
                self._logger.debug("Field : {0} has no value".format(field.id))
                hasValue = False

        if not hasValue:
            raise Exception("Expected value cannot be computed, some dependencies are missing for domain {0}".format(self))
        else:
            size = 0
            for field in self.fieldDependencies:
                if field.domain is self:
                    fieldValue = self.dataType.generate()
                else:
                    fieldValue = parsingPath.getDataAssignedToVariable(field.domain)
                if fieldValue is None:
                    break
                else:
                    tmpLen = len(fieldValue)
                    size += tmpLen


            size = int(size * self.factor + self.offset)
            size_raw = TypeConverter.convert(size, Integer, Raw, src_unitSize=self.dataType.unitSize)        
            b = TypeConverter.convert(size_raw, Raw, BitArray)
            
            # add heading '0'
            while len(b)<self.dataType.size[0]:
                b.insert(0, False)

            # in some cases (when unitSize and size are not equal), it may require to delete some '0' in front
            while len(b)>self.dataType.size[0]:
                b.remove(0)
        return b
开发者ID:chubbymaggie,项目名称:netzob,代码行数:38,代码来源:Size.py



注:本文中的netzob.Common.Models.Types.TypeConverter.TypeConverter类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python ResourcesConfiguration.ResourcesConfiguration类代码示例发布时间:2022-05-27
下一篇:
Python AbstractType.AbstractType类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap