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

Python six.iterbytes函数代码示例

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

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



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

示例1: encrypt

 def encrypt(self, value):
     value_s = six.iterbytes(value)
     repeated_iv = six.iterbytes(list(int(math.ceil(float(len(value)) / len(self.iv))) * self.iv))
     repeated_password = six.iterbytes(list(int(math.ceil(float(len(value)) / len(self.password))) * self.password))
     xor1 = [a ^ b for a, b in zip(value_s, repeated_iv)]
     xor2 = [a ^ b for a, b in zip(xor1, repeated_password)]
     return b''.join(map(six.int2byte, xor2))
开发者ID:Yelp,项目名称:send_nsca,代码行数:7,代码来源:nsca.py


示例2: _constant_time_compare

def _constant_time_compare(a, b):
    if len(a) != len(b):
        return False
    result = 0
    for x, y in zip(six.iterbytes(a), six.iterbytes(b)):
        result |= x ^ y
    return result == 0
开发者ID:mrphishxxx,项目名称:python-triplesec,代码行数:7,代码来源:utils.py


示例3: nasm_null_safe_mutable_data_finalizer

def nasm_null_safe_mutable_data_finalizer(env, code, data):
    """
    Simple data allocation strategy that expects the code to be in a writable
    segment. We just append the data to the end of the code.
    """

    if data or env.buffers:
        # Determine length of nullify + shellcode and adjust data pointer
        xor_offsets = []
        masked_data = OrderedDict()

        for datum, (offset, orig_datum) in six.iteritems(data):
            xor_offsets.extend([
                                   offset + i
                                   for i, b in enumerate(six.iterbytes(datum))
                                   if b in (0, 10, 13)
                                   ])

            masked_datum = b''.join([
                                        six.int2byte(b) if b not in (0, 10, 13)
                                        else six.int2byte(b ^ 0xff)
                                        for b in six.iterbytes(datum)
                                        ])
            masked_data[masked_datum] = (offset, orig_datum)

        if xor_offsets:
            # Build code to restore NUL, \r and \n
            temp_reg = env.TEMP_REG[env.target.bits]
            null_code = env.reg_load(env.BL, 255) + \
                        env.reg_load(temp_reg, env.OFFSET_REG)

            last_offset = 0
            for offset in xor_offsets:
                offset -= last_offset
                null_code.extend(
                    env.reg_add(temp_reg, offset) +
                    ['xor [%s], bl' % temp_reg]
                )
                last_offset += offset
            code = ['\t%s' % line for line in null_code] + code
            data = masked_data

        code_len = len(asm('\n'.join(code), target=env.target))
        adjust_ebp = env.reg_add(env.OFFSET_REG, code_len)

        return [
            '\tjmp __getpc1',
            '__getpc0:',
            '\tpop %s' % env.OFFSET_REG,
        ] + [
            '\t%s' % line for line in adjust_ebp
        ] + [
            '\tjmp __realstart',
            '__getpc1:',
            '\tcall __getpc0',
            '__realstart:',
        ] + code + _pack_data(data)
    else:
        return code
开发者ID:BruceLEO1969,项目名称:pwnypack,代码行数:59,代码来源:mutable_data.py


示例4: constant_time_compare

def constant_time_compare(val1, val2):
    """
    Returns True if the two strings are equal, False otherwise.

    The time taken is independent of the number of characters that match.
    """
    if len(val1) != len(val2):
        return False
    result = 0
    for x, y in zip(six.iterbytes(val1), six.iterbytes(val2)):
        result |= x ^ y
    return result == 0
开发者ID:zopefoundation,项目名称:AuthEncoding,代码行数:12,代码来源:AuthEncoding.py


示例5: read_loose

def read_loose(stream):
    """Turn a HL7-like blob of text into a real HL7 messages"""
    # look for the START_BLOCK to delineate messages
    START_BLOCK = b'MSH|^~\&|'

    # load all the data
    data = stream.read()

    # take out all the typical MLLP separators. In Python 3, iterating
    # through a bytestring returns ints, so we need to filter out the int
    # versions of the separators, then convert back from a list of ints to
    # a bytestring (In Py3, we could just call bytes([ints]))
    separators = [six.byte2int(bs) for bs in [EB, FF, SB]]
    data = b''.join([six.int2byte(c) for c in six.iterbytes(data) if c not in separators])

    # Windows & Unix new lines to segment separators
    data = data.replace(b'\r\n', b'\r').replace(b'\n', b'\r')

    for m in data.split(START_BLOCK):
        if not m:
            # the first element will not have any data from the split
            continue

        # strip any trailing whitespace
        m = m.strip(CR + b'\n ')

        # re-insert the START_BLOCK, which was removed via the split
        yield START_BLOCK + m
开发者ID:jgambox,项目名称:python-hl7,代码行数:28,代码来源:client.py


示例6: nthash

def nthash(password=b''):
    """Generates nt md4 password hash for a given password."""

    password = password[:128]
    password = b''.join([
        six.int2byte(c) + b'\000' for c in six.iterbytes(password)])
    return md4.new(password).hexdigest().translate(toupper).encode('ascii')
开发者ID:cwaldbieser,项目名称:ldaptor,代码行数:7,代码来源:smbpassword.py


示例7: emit_repr

def emit_repr(data, width=0, message=' .. skipped {leftover} chars .. ', padding=' ', **formats):
    """Return a string replaced with ``message`` if larger than ``width``

    Message can contain the following format operands:
    width = width to be displayed
    charwidth = width of each character
    bytewidth = number of bytes that can fit within width
    length = number of bytes displayed
    leftover = approximate number of bytes skipped
    **format = extra format specifiers for message
    """
    size = len(data)
    charwidth = len(r'\xFF')
    bytewidth = width / charwidth
    leftover = size - bytewidth

    hexify = lambda s: str().join(map(r'\x{:02x}'.format, six.iterbytes(s)))

    if width <= 0 or bytewidth >= len(data):
        return hexify(data)

    # FIXME: the skipped/leftover bytes are being calculated incorrectly..
    msg = message.format(size=size, charwidth=charwidth, width=width, leftover=leftover, **formats)

    # figure out how many bytes we can print
    bytefrac,bytewidth = math.modf((width - len(msg)) * 1.0 / charwidth)
    padlength = math.trunc(charwidth*bytefrac)

    msg = padding*math.trunc(padlength/2.0+0.5) + msg + padding*math.trunc(padlength/2)
    left,right = data[:math.trunc(bytewidth/2 + 0.5)], data[size-math.trunc(bytewidth/2):]
    return hexify(left) + msg + hexify(right)
开发者ID:arizvisa,项目名称:syringe,代码行数:31,代码来源:utils.py


示例8: write_dap_register

 def write_dap_register(self, port, addr, value):
     assert ((addr & 0xf0) == 0) or (port != self.DP_PORT), "banks are not allowed for DP registers"
     assert (addr >> 16) == 0, "register address must be 16-bit"
     cmd = [Commands.JTAG_COMMAND, Commands.JTAG_WRITE_DAP_REG]
     cmd.extend(six.iterbytes(struct.pack('<HHI', port, addr, value)))
     response = self._device.transfer(cmd, readSize=2)
     self._check_status(response)
开发者ID:mesheven,项目名称:pyOCD,代码行数:7,代码来源:stlink.py


示例9: xor

def xor(key, data):
    """
    Perform cyclical exclusive or operations on ``data``.

    The ``key`` can be a an integer *(0 <= key < 256)* or a byte sequence. If
    the key is smaller than the provided ``data``, the ``key`` will be
    repeated.

    Args:
        key(int or bytes): The key to xor ``data`` with.
        data(bytes): The data to perform the xor operation on.

    Returns:
        bytes: The result of the exclusive or operation.

    Examples:
        >>> from pwny import *
        >>> xor(5, b'ABCD')
        b'DGFA'
        >>> xor(5, b'DGFA')
        b'ABCD'
        >>> xor(b'pwny', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
        b'15-=51)19=%5=9!)!%=-%!9!)-'
        >>> xor(b'pwny', b'15-=51)19=%5=9!)!%=-%!9!)-')
        b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    """

    if type(key) is int:
        key = six.int2byte(key)
    key_len = len(key)

    return b''.join(
        six.int2byte(c ^ six.indexbytes(key, i % key_len))
        for i, c in enumerate(six.iterbytes(data))
    )
开发者ID:pombredanne,项目名称:pwnypack,代码行数:35,代码来源:codec.py


示例10: _write_mem

 def _write_mem(self, addr, data, memcmd, max, apsel):
     with self._lock:
         while len(data):
             thisTransferSize = min(len(data), max)
             thisTransferData = data[:thisTransferSize]
         
             cmd = [Commands.JTAG_COMMAND, memcmd]
             cmd.extend(six.iterbytes(struct.pack('<IHB', addr, thisTransferSize, apsel)))
             self._device.transfer(cmd, writeData=thisTransferData)
         
             addr += thisTransferSize
             data = data[thisTransferSize:]
         
             # Check status of this write.
             response = self._device.transfer([Commands.JTAG_COMMAND, Commands.JTAG_GETLASTRWSTATUS2], readSize=12)
             status, _, faultAddr = struct.unpack('<HHI', response[0:8])
             
             # Handle transfer faults specially so we can assign the address info.
             if status != Status.JTAG_OK:
                 error_message = Status.get_error_message(status)
                 if status in self._MEM_FAULT_ERRORS:
                     # Clear sticky errors.
                     self._clear_sticky_error()
             
                     exc = exceptions.TransferFaultError()
                     exc.fault_address = faultAddr
                     exc.fault_length = thisTransferSize - (faultAddr - addr)
                     raise exc
                 elif status in self._ERROR_CLASSES:
                     raise self._ERROR_CLASSES[status](error_message)
                 elif status != Status.JTAG_OK:
                     raise exceptions.ProbeError(error_message)
开发者ID:flit,项目名称:pyOCD,代码行数:32,代码来源:stlink.py


示例11: load_from_file

 def load_from_file(self, filename, offset = 0):
     """ Load this ROM with the contents of a file. """
     with open(filename, "rb") as fileptr:
         data = fileptr.read()
         
     for index, byte in enumerate(six.iterbytes(data), start = offset):
         self.contents[index] = byte
开发者ID:astamp,项目名称:PyXT,代码行数:7,代码来源:memory.py


示例12: run

    def run(self):
        """Overrides base class run method. Do not call directly."""
        settings = self.serial_port.getSettingsDict()
        settings["timeout"] = 0.1  # seconds
        self.serial_port.applySettingsDict(settings)
        self._ready()
        while not self.finished.isSet():
            # Grab data from the serial port, or wait for timeout if none available.
            raw = self.serial_port.read(max(1, self.serial_port.inWaiting()))

            if not raw and len(self._pressed_keys) > 0:
                self._finish_stroke()
                continue

            for byte in iterbytes(raw):
                key_set = byte >> 6
                if key_set <= self._last_key_set and len(self._pressed_keys) > 0:
                    self._finish_stroke()
                self._last_key_set = key_set
                for i in range(6):
                    if (byte >> i) & 1:
                        self._pressed_keys.append(STENO_KEY_CHART[(key_set * 6) + i])
                if 3 == key_set:
                    # Last possible set, the stroke is finished.
                    self._finish_stroke()
开发者ID:openstenoproject,项目名称:plover,代码行数:25,代码来源:txbolt.py


示例13: ascii85decode

def ascii85decode(data):
    """
    In ASCII85 encoding, every four bytes are encoded with five ASCII
    letters, using 85 different types of characters (as 256**4 < 85**5).
    When the length of the original bytes is not a multiple of 4, a special
    rule is used for round up.

    The Adobe's ASCII85 implementation is slightly different from
    its original in handling the last characters.

    """
    n = b = 0
    out = b''
    for i in six.iterbytes(data):
        c=six.int2byte(i)
        if b'!' <= c and c <= b'u':
            n += 1
            b = b*85+(ord(c)-33)
            if n == 5:
                out += struct.pack('>L', b)
                n = b = 0
        elif c == b'z':
            assert n == 0, str(n)
            out += b'\0\0\0\0'
        elif c == b'~':
            if n:
                for _ in range(5-n):
                    b = b*85+84
                out += struct.pack('>L', b)[:n-1]
            break
    return out
开发者ID:goulu,项目名称:pdfminer,代码行数:31,代码来源:ascii85.py


示例14: fnv1a

 def fnv1a(d):
     h = FNV_32_INIT
     for c in six.iterbytes(d):
         h ^= c
         h *= FNV_32_PRIME
         h &= 0xffffffff
     return h
开发者ID:douban,项目名称:dpark,代码行数:7,代码来源:beansdb.py


示例15: crc16_kermit

def crc16_kermit(data, crc=0):
    """Calculate/Update the Kermit CRC16 checksum for some data"""
    tab = CRC16_KERMIT_TAB  # minor optimization (now in locals)
    for byte in six.iterbytes(data):
        tbl_idx = (crc ^ byte) & 0xff
        crc = (tab[tbl_idx] ^ (crc >> 8)) & 0xffff
    return crc & 0xffff
开发者ID:posborne,项目名称:python-suitcase,代码行数:7,代码来源:crc.py


示例16: decode

def decode(s):
    """Decode a folder name from IMAP modified UTF-7 encoding to unicode.

    Input is bytes (Python 3) or str (Python 2); output is always
    unicode. If non-bytes/str input is provided, the input is returned
    unchanged.
    """

    if not isinstance(s, binary_type):
        return s

    r = []
    _in = bytearray()
    for c in iterbytes(s):
        if c == AMPERSAND_ORD and not _in:
            _in.append(c)
        elif c == DASH_ORD and _in:
            if len(_in) == 1:
                r.append('&')
            else:
                r.append(modified_deutf7(_in[1:]))
            _in = bytearray()
        elif _in:
            _in.append(c)
        else:
            r.append(unichr(c))
    if _in:
        r.append(modified_deutf7(_in[1:]))
    return ''.join(r)
开发者ID:bechtoldt,项目名称:imapclient,代码行数:29,代码来源:imap_utf7.py


示例17: feed

 def feed(self, data):
     """
     Feed data to the parser.
     """
     assert isinstance(data, binary_type)
     for b in iterbytes(data):
         self._parser.send(int2byte(b))
开发者ID:0038lana,项目名称:Test-Task,代码行数:7,代码来源:protocol.py


示例18: extend

 def extend(self, values):
     if isinstance(values, six.text_type):
         self.__text += values
     else:
         assert isinstance(values, six.binary_type)
         for b in six.iterbytes(values):
             self.append(b)
开发者ID:JuviAndaya,项目名称:chellow,代码行数:7,代码来源:reader.py


示例19: decode

    def decode(self, codepoints):
        """
        Given an iterable of integer codepoints, yields the
        corresponding bytes, one at a time, as byte strings of length
        E{1}. Retains the state of the codebook from call to call, so
        if you have another stream, you'll likely need another
        decoder!

        Decoders will NOT handle END_OF_INFO_CODE (rather, they will
        handle the code by throwing an exception); END_OF_INFO should
        be handled by the upstream codepoint generator (see
        L{BitUnpacker}, for example)

        >>> import lzw
        >>> dec = lzw.Decoder()
        >>> result = b''.join(dec.decode([103, 97, 98, 98, 97, 32, 258, 260, 262, 121, 111, 263, 259, 261, 256]))
        >>> result == b'gabba gabba yo gabba'
        True

        """
        codepoints = [ cp for cp in codepoints ]

        for cp in codepoints:
            decoded = self._decode_codepoint(cp)
            for character in six.iterbytes(decoded):
                # TODO optimize, casting back to bytes when bytes above
                yield six.int2byte(character)
开发者ID:joeatwork,项目名称:python-lzw,代码行数:27,代码来源:__init__.py


示例20: _generate_kernel_bin

 def _generate_kernel_bin(self, k, ctx):
     gk = gpuarray.GpuKernel(k.code, k.name, k.params, context=ctx,
                             **k.flags)
     bin = gk._binary
     bcode = ','.join(hex(c) for c in iterbytes(bin))
     return ("""static const char %(bname)s[] = { %(bcode)s };""" %
             dict(bname=k.binvar, bcode=bcode))
开发者ID:5730279821-TA,项目名称:Theano,代码行数:7,代码来源:basic_ops.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python six.iteritems函数代码示例发布时间:2022-05-27
下一篇:
Python six.int2byte函数代码示例发布时间: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