Example #1
0
def decipher(v, k):
    """
    TEA decipher, decrypt  64bits value with 128 bits key.
    TEA 解密程序, 用128比特密钥, 解密64比特值

    it's the inverse function of TEA encrypt.
    他是TEA加密函数的反函数.

    >>> c = code('abcdefgh', 'aaaabbbbccccdddd')
    >>> decipher( c, 'aaaabbbbccccdddd')
    'abcdefgh'
    """

    n = 16
    y, z = _unpack('>LL', v[0:8])
    a, b, c, d = _unpack('>LLLL', k[0:16])
    delta = 0x9E3779B9L
    s = (delta << 4) & op
    for i in xrange(n):
        z -= ((y << 4) + c) ^ (y + s) ^ ((y >> 5) + d)
        z &= op
        y -= ((z << 4) + a) ^ (z + s) ^ ((z >> 5) + b)
        y &= op
        s -= delta
        s &= op
    return _pack('>LL', y, z)
Example #2
0
    def _pkt_T(self):
        #
        # Row Description
        #
        nFields = _unpack('!h', self.__read_bytes(2))[0]
        descr = []
        for i in range(nFields):
            fieldname = self.__read_string()
            oid, type_size, type_modifier = _unpack('!ihi',
                                                    self.__read_bytes(10))
            descr.append((fieldname, oid, type_size, type_modifier))

        description = []
        for name, oid, size, modifier in descr:
            pg_type = self._oid_map.get(oid, _DEFAULT_PGTYPE)
            description.append(
                (name, pg_type.type_id, None, None, None, None, None))

        # Save the field description list
        self.__current_result.set_description(description)

        # build a list of field conversion functions we can use against each row
        self.__current_result.conversion = [
            self._get_conversion(d[1]) for d in descr
        ]
Example #3
0
def _parseapetag(data):
    '''Parse an APEv2 tag and return a dictionary of tag fields'''
    apeitems = {}
    numitems = _unpack("<i", data[16:20])[0]
    if numitems > _maxapeitems:
        raise TagError, 'Tag exceeds maximum allowed item count'
    if numitems != _unpack("<i", data[-16:-12])[0]:
        raise TagError, 'Corrupt tag, mismatched header and footer item count'
    # 32 is size of footer, 11 is minimum item length item
    if numitems > (len(data) - 32) / 11:
        raise TagError, 'Corrupt tag, specifies more items that is possible ' \
                        'given space remaining: %i items' % numitems
    curpos = 32
    tagitemend = len(data) - 32
    for x in range(numitems):
        if curpos >= tagitemend:
            raise TagError, 'Corrupt tag, end of tag reached with more items ' \
                            'specified'
        item = ApeItem()
        curpos = item.parsetag(data, curpos)
        itemkey = item.key.lower()
        if itemkey in apeitems:
            raise TagError, 'Corrupt tag, duplicate item key: %r' % itemkey
        apeitems[itemkey] = item
    if tagitemend - curpos:
        raise TagError, 'Corrupt tag, parsing complete but not at end ' \
            'of input: %i bytes remaining' % (len(data) - curpos)
    return apeitems
Example #4
0
def code(v, k):
    """
    TEA coder encrypt 64 bits value, by 128 bits key,
    QQ do 16 round TEA.
    To see:
    http://www.ftp.cl.cam.ac.uk/ftp/papers/djw-rmn/djw-rmn-tea.html .

    TEA 加密,  64比特明码, 128比特密钥, qq的TEA算法使用16轮迭代
    具体参看
    http://www.ftp.cl.cam.ac.uk/ftp/papers/djw-rmn/djw-rmn-tea.html
    >>> c = code('abcdefgh', 'aaaabbbbccccdddd')
    >>> b2a_hex(c)
    'a557272c538d3e96'
    """
    n=16  #qq use 16
    delta = 0x9e3779b9
    k = _unpack('>LLLL', k[0:16])
    y, z = _unpack('>LL', v[0:8])
    s = 0
    for i in range(n):
        s += delta
        y += (op &(z<<4))+ k[0] ^ z+ s ^ (op&(z>>5)) + k[1] ;
        y &= op
        z += (op &(y<<4))+ k[2] ^ y+ s ^ (op&(y>>5)) + k[3] ;
        z &= op
    r = _pack('>LL',y,z)
    return r
Example #5
0
def inet_ntop(af, packed_ip):
    """Convert an packed IP address of the given family to string format."""
    if af == AF_INET:
        #   IPv4.
        return inet_ntoa(packed_ip)
    elif af == AF_INET6:
        #   IPv6.
        if len(packed_ip) != 16 or not hasattr(packed_ip, 'split'):
            raise ValueError('invalid length of packed IP address string')

        tokens = ['%x' % i for i in _unpack('>8H', packed_ip)]

        #   Convert packed address to an integer value.
        words = list(_unpack('>8H', packed_ip))
        int_val = 0
        for i, num in enumerate(reversed(words)):
            word = num
            word = word << 16 * i
            int_val = int_val | word

        if 0xffff < int_val <= 0xffffffff or int_val >> 32 == 0xffff:
            #   IPv4 compatible / mapped IPv6.
            packed_ipv4 = _pack('>2H', *[int(i, 16) for i in tokens[-2:]])
            ipv4_str = inet_ntoa(packed_ipv4)
            tokens = tokens[0:-2] + [ipv4_str]

        return ':'.join(_compact_ipv6_tokens(tokens))
    else:
        raise ValueError('unknown address family %d' % af)
Example #6
0
def inet_ntop(af, packed_ip):
    """Convert an packed IP address of the given family to string format."""
    if af == AF_INET:
        #   IPv4.
        return inet_ntoa(packed_ip)
    elif af == AF_INET6:
        #   IPv6.
        if len(packed_ip) != 16 or not hasattr(packed_ip, 'split'):
            raise ValueError('invalid length of packed IP address string')

        tokens = ['%x' % i for i in _unpack('>8H', packed_ip)]

        #   Convert packed address to an integer value.
        words = list(_unpack('>8H', packed_ip))
        int_val = 0
        for i, num in enumerate(reversed(words)):
            word = num
            word = word << 16 * i
            int_val = int_val | word

        if 0xffff < int_val <= 0xffffffff or int_val >> 32 == 0xffff:
            #   IPv4 compatible / mapped IPv6.
            packed_ipv4 = _pack('>2H', *[int(i, 16) for i in tokens[-2:]])
            ipv4_str = inet_ntoa(packed_ipv4)
            tokens = tokens[0:-2] + [ipv4_str]

        return ':'.join(_compact_ipv6_tokens(tokens))
    else:
        raise ValueError('unknown address family %d' % af)
Example #7
0
def _parseapetag(data):
    '''Parse an APEv2 tag and return a dictionary of tag fields'''
    apeitems = {}
    numitems = _unpack("<i",data[16:20])[0]
    if numitems != _unpack("<i",data[-16:-12])[0]:
        raise TagError, 'Corrupt tag, mismatched header and footer item count' 
    # 32 is size of footer, 11 is minimum item length item
    if numitems > (len(data) - 32)/11:
        raise TagError, 'Corrupt tag, specifies more items that is possible ' \
                        'given space remaining: %i items' % numitems
    curpos = 32
    tagitemend = len(data) - 32
    for x in range(numitems):
        if curpos >= tagitemend:
            raise TagError, 'Corrupt tag, end of tag reached with more items' \
                            'specified'
        item = ApeItem()
        curpos = item.parsetag(data, curpos)
        itemkey = item.key.lower()
        if itemkey in apeitems:
            raise TagError, 'Corrupt tag, duplicate item key: %r' % itemkey
        apeitems[itemkey] = item
    if tagitemend - curpos:
        raise TagError, 'Corrupt tag, parsing complete but not at end ' \
            'of input: %i bytes remaining' % (len(data) - curpos)
    return apeitems
Example #8
0
def decipher(v, k):
    """
    TEA decipher, decrypt  64bits value with 128 bits key.
    TEA 解密程序, 用128比特密钥, 解密64比特值

    it's the inverse function of TEA encrypt.
    他是TEA加密函数的反函数.

    >>> c = code('abcdefgh', 'aaaabbbbccccdddd')
    >>> decipher( c, 'aaaabbbbccccdddd')
    'abcdefgh'
    """

    n = 16
    y, z = _unpack('>LL', v[0:8])
    a, b, c, d = _unpack('>LLLL', k[0:16])
    delta = 0x9E3779B9L;
    s = (delta << 4)&op
    for i in xrange(n):
        z -= ((y<<4)+c) ^ (y+s) ^ ((y>>5) + d)
        z &= op
        y -= ((z<<4)+a) ^ (z+s) ^ ((z>>5) + b)
        y &= op
        s -= delta
        s &= op
    return _pack('>LL', y, z)
Example #9
0
def encipher(v, k):
    """
    TEA encipher encrypt 64 bits value, by 128 bits key,
    QQ do 16 round TEA.
    To see:
    http://www.ftp.cl.cam.ac.uk/ftp/papers/djw-rmn/djw-rmn-tea.html .
    TEA 加密,  64比特明码, 128比特密钥, qq的TEA算法使用16轮迭代
    具体参看
    http://www.ftp.cl.cam.ac.uk/ftp/papers/djw-rmn/djw-rmn-tea.html
    >>> c = encipher('abcdefgh', 'aaaabbbbccccdddd')
    >>> b2a_hex(c)
    'a557272c538d3e96'
    """
    n = 16
    delta = 0x9e3779b9L
    k = _unpack('>LLLL', k[0:16])
    y, z = _unpack('>LL', v[0:8])
    s = 0
    for i in xrange(n):
        s += delta
        y += (op & (z << 4)) + k[0] ^ z + s ^ (op & (z >> 5)) + k[1]
        y &= op
        z += (op & (y << 4)) + k[2] ^ y + s ^ (op & (y >> 5)) + k[3]
        z &= op
    r = _pack('>LL', y, z)
    return r
Example #10
0
def process_notification(device, status, notification, feature):
    global keys_down, g_keys_down, m_keys_down, mr_key_down, key_down, key_up
    key_down, key_up = None, None
    # need to keep track of keys that are down to find a new key down
    if feature == _F.REPROG_CONTROLS_V4 and notification.address == 0x00:
        new_keys_down = _unpack('!4H', notification.data[:8])
        for key in new_keys_down:
            if key and key not in keys_down:
                key_down = key
        for key in keys_down:
            if key and key not in new_keys_down:
                key_up = key
        keys_down = new_keys_down
    # and also G keys down
    elif feature == _F.GKEY and notification.address == 0x00:
        new_g_keys_down = _unpack('!4B', notification.data[:4])
        # process 32 bits, byte by byte
        for byte_idx in range(4):
            new_byte, old_byte = new_g_keys_down[byte_idx], g_keys_down[
                byte_idx]
            for i in range(1, 9):
                if new_byte & (0x01 << (i - 1)) and not old_byte & (0x01 <<
                                                                    (i - 1)):
                    key_down = _CONTROL['G' + str(i + 8 * byte_idx)]
                if old_byte & (0x01 << (i - 1)) and not new_byte & (0x01 <<
                                                                    (i - 1)):
                    key_up = _CONTROL['G' + str(i + 8 * byte_idx)]
        g_keys_down = new_g_keys_down
    # and also M keys down
    elif feature == _F.MKEYS and notification.address == 0x00:
        new_m_keys_down = _unpack('!1B', notification.data[:1])[0]
        for i in range(1, 9):
            if new_m_keys_down & (0x01 <<
                                  (i - 1)) and not m_keys_down & (0x01 <<
                                                                  (i - 1)):
                key_down = _CONTROL['M' + str(i)]
            if m_keys_down & (0x01 <<
                              (i - 1)) and not new_m_keys_down & (0x01 <<
                                                                  (i - 1)):
                key_up = _CONTROL['M' + str(i)]
        m_keys_down = new_m_keys_down
    # and also MR key
    elif feature == _F.MR and notification.address == 0x00:
        new_mr_key_down = _unpack('!1B', notification.data[:1])[0]
        if not mr_key_down and new_mr_key_down:
            key_down = _CONTROL['MR']
        if mr_key_down and not new_mr_key_down:
            key_up = _CONTROL['MR']
        mr_key_down = new_mr_key_down
    GLib.idle_add(rules.evaluate, feature, notification, device, status, True)
Example #11
0
def code(v, k):
    n = 16  # qq use 16
    delta = 0x9e3779b9L
    k = _unpack('>LLLL', k[0:16])
    y, z = _unpack('>LL', v[0:8])
    s = 0
    for i in xrange(n):
        s += delta
        y += (op & (z << 4)) + k[0] ^ z + s ^ (op & (z >> 5)) + k[1];
        y &= op
        z += (op & (y << 4)) + k[2] ^ y + s ^ (op & (y >> 5)) + k[3];
        z &= op
    r = _pack('>LL', y, z)
    return r
Example #12
0
def _get_clock():
    global _static_last_sec, _static_last_msec, _static_adjustment, _static_clock_seq
    sec, msec = _gettimeofday()
    try_again = True
    while try_again:
        try_again = False
        if _static_last_sec == 0 and _static_last_msec == 0:
            _static_clock_seq = _unpack(">H", _get_random_bytes(2))[0] & 0x1FFF
            _static_last_sec = sec - 1
            _static_last_msec = msec
        if sec < _static_last_sec or ((sec == _static_last_sec) and
                                      (msec < _static_last_msec)):
            _static_clock_seq = (_static_clock_seq + 1) & 0x1FFF
            _static_adjustment = 0
            _static_last_sec = sec
            _static_last_msec = msec
        elif sec == _static_last_sec and msec == _static_last_msec:
            if _static_adjustment >= _MAX_ADJUSTMENT:
                try_again = True
            else:
                _static_adjustment += 1
        else:
            _static_adjustment = 0
            _static_last_sec = sec
            _static_last_msec = msec
    clock_reg = msec * 10 + _static_adjustment
    clock_reg = (clock_reg + sec * 10000000) & 0xFFFFFFFFFFFFFFFFL
    clock_reg = (clock_reg +
                 (((0x01B21DD2L) << 32) + 0x13814000L)) & 0xFFFFFFFFFFFFFFFFL
    return (clock_reg >> 32), (clock_reg & 0xFFFFFFFFL), _static_clock_seq
Example #13
0
def _get_random_bytes(n):
    reader = _get_random_reader()
    buf = ''
    if reader:
        loose_counter = 0
        while len(buf) != n:
            buf += reader(n)

            if loose_counter > 10:
                break
            loose_counter += 1
    d = n-len(buf)

    if d>0:
        buf += '\0'*d

    if n==16:
        fmt = _fmt_16

    elif n==6:
        fmt = _fmt_6

    elif n==2:
        fmt = _fmt_2

    else:
        fmt = ">%sB" % n
    return _pack(fmt,*tuple(map(_randomize_byte,_unpack(fmt,buf))))
Example #14
0
def unpack(fmt, bs):
    ##from cs.logutils import X
    ##X("py3_for2.unpack: fmt=%r, bs=%r", fmt, bs)
    if isinstance(bs, bytes):
        bs = bs._bytes__s
        ##X("py3_for2.unpack: bs => %r", bs)
    return _unpack(fmt, bs)
Example #15
0
    def _pkt_T(self):
        #
        # Row Description
        #
        nFields = _unpack("!h", self.__read_bytes(2))[0]
        descr = []
        for i in range(nFields):
            fieldname = self.__read_string()
            oid, type_size, type_modifier = _unpack("!ihi", self.__read_bytes(10))
            descr.append((fieldname, oid, type_size, type_modifier))

        # Save the field description list
        self.__current_result.set_description(descr)

        # build a list of field conversion functions we can use against each row
        self.__current_result.conversion = [self.__type_oid_conversion.get(d[1], _identity) for d in descr]
def inet_ntoa(packed_ip):
    """
    Convert an IP address from 32-bit packed binary format to string format.
    """
    if len(packed_ip) != 4 or not hasattr(packed_ip, 'split'):
        raise ValueError('invalid length of packed IP address string')
    return '%d.%d.%d.%d' % _unpack('4B', packed_ip)
Example #17
0
 def parsetag(self, data, curpos):
     '''Parse next tag from data string, starting at current position'''
     del self[:]
     itemlength = _unpack("<i", data[curpos:curpos + 4])[0]
     if itemlength < 0:
         raise TagError, 'Corrupt tag, invalid item length at position ' \
                         '%i: %i bytes' % (curpos, itemlength)
     if data[curpos + 4:curpos + 7] != '\x00\x00\x00':
         raise TagError, 'Corrupt tag, invalid item flags, bits 8-31 ' \
                         'nonzero at position %i' % curpos
     type, readonly = divmod(ord(data[curpos + 7]), 2)
     if type > 3:
         raise TagError, 'Corrupt tag, invalid item flags, bits 3-7 ' \
                         'nonzero at position %i' % curpos
     self.type = _apeitemtypes[type]
     self.readonly = bool(readonly)
     curpos += 8
     keyend = data.find("\x00", curpos)
     if keyend < curpos:
         raise TagError, 'Corrupt tag, unterminated item key at position ' \
                         '%i' % curpos
     itemkey = data[curpos:keyend]
     if not self.validkey(itemkey):
         raise TagError, 'Corrupt tag, invalid item key at position ' \
                         '%i: %r' % (curpos, itemkey)
     self.key = itemkey
     curpos = keyend + itemlength + 1
     itemvalue = data[keyend + 1:curpos]
     if self.type == 'utf8' or self.type == 'external':
         self.extend(itemvalue.decode('utf8').split('\x00'))
     else:
         self.append(itemvalue)
     return curpos
Example #18
0
def read_n_bytes(fileHandle, formatChar):
    """read n bytes from file. The number of bytes read is specified by the
    ``formatChar``
    
    Parameters
    ----------
    fileHandle : object
        file handle object
    formatChar : string
        format character -- 'c' (1), 'h' (2), 'i' (4), 'I' (4), 'd' (8), 'f' (4)
        
    Returns
    -------
    nbytes : 
    """
    nbytes = None
    bytes2read = {'c': 1, 'h': 2, 'i': 4, 'I': 4, 'd': 8, 'f': 4}
    packedBytes = fileHandle.read(bytes2read[formatChar])
    if packedBytes:
        try:
            nbytes = _unpack(formatChar, packedBytes)[0]
        except Exception as e:
            print("Reading bytes from file failed at position {}".format(
                fileHandle.tell()))
            print("packedBytes = {} of len {}".format(packedBytes,
                                                      len(packedBytes)))
            raise e
    return nbytes
Example #19
0
    def _pkt_R(self):
        #
        # Startup Response
        #
        code = _unpack('!i', self.__read_bytes(4))[0]
        if code == 0:
            self.__authenticated = 1
            #print 'Authenticated!'
        elif code == 1:
            raise InterfaceError('Kerberos V4 authentication is required by server, but not supported by this client')
        elif code == 2:
            raise InterfaceError('Kerberos V5 authentication is required by server, but not supported by this client')
        elif code == 3:
            self.__send(_pack('!i', len(self.__passwd)+5) + self.__passwd + '\0')
        elif code == 4:
            salt = self.__read_bytes(2)
            try:
                import crypt
            except:
                raise InterfaceError('Encrypted authentication is required by server, but Python crypt module not available')
            cpwd = crypt.crypt(self.__passwd, salt)
            self.__send(_pack('!i', len(cpwd)+5) + cpwd + '\0')
        elif code == 5:
            import md5

            m = md5.new(self.__passwd + self.__userid).hexdigest()
            m = md5.new(m + self.__read_bytes(4)).hexdigest()
            m = 'md5' + m + '\0'
            self.__send(_pack('!i', len(m)+4) + m)
        else:
            raise InterfaceError('Unknown startup response code: R%d (unknown password encryption?)' % code)
    def _pkt_T(self):
        #
        # Row Description
        #
        nFields = _unpack('!h', self.__read_bytes(2))[0]
        descr = []
        for i in range(nFields):
            fieldname = self.__read_string()
            oid, type_size, type_modifier = _unpack('!ihi', self.__read_bytes(10))
            descr.append((fieldname, oid, type_size, type_modifier))

        # Save the field description list
        self.__current_result.set_description(descr)

        # build a list of field conversion functions we can use against each row
        self.__current_result.conversion = [self.__type_oid_conversion.get(d[1], _identity) for d in descr]
Example #21
0
def read_n_bytes(fileHandle, formatChar):
    """read n bytes from file. The number of bytes read is specified by the
    ``formatChar``
    
    Parameters
    ----------
    fileHandle : object
        file handle object
    formatChar : string
        format character -- 'c' (1), 'h' (2), 'i' (4), 'I' (4), 'd' (8), 'f' (4)
        
    Returns
    -------
    nbytes : 
    """
    nbytes = None    
    bytes2read = {'c':1, 'h':2, 'i':4, 'I':4, 'd':8, 'f':4}    
    packedBytes = fileHandle.read(bytes2read[formatChar])
    if packedBytes:
        try:
            nbytes = _unpack(formatChar, packedBytes)[0]
        except Exception as e:
            print("Reading bytes from file failed at position {}".format(fileHandle.tell()))
            print("packedBytes = {} of len {}".format(packedBytes, len(packedBytes)))
            raise e
    return nbytes 
Example #22
0
def get_firmware(device):
	"""Reads a device's firmware info.

	:returns: a list of FirmwareInfo tuples, ordered by firmware layer.
	"""
	count = feature_request(device, FEATURE.FIRMWARE)
	if count:
		count = ord(count[:1])

		fw = []
		for index in range(0, count):
			fw_info = feature_request(device, FEATURE.FIRMWARE, 0x10, index)
			if fw_info:
				level = ord(fw_info[:1]) & 0x0F
				if level == 0 or level == 1:
					name, version_major, version_minor, build = _unpack(b'!3sBBH', fw_info[1:8])
					version = '%02X.%02X' % (version_major, version_minor)
					if build:
						version += '.B%04X' % build
					extras = fw_info[9:].rstrip(b'\x00') or None
					fw_info = _FirmwareInfo(FIRMWARE_KIND[level], name.decode('ascii'), version, extras)
				elif level == FIRMWARE_KIND.Hardware:
					fw_info = _FirmwareInfo(FIRMWARE_KIND.Hardware, '', ord(fw_info[1:2]), None)
				else:
					fw_info = _FirmwareInfo(FIRMWARE_KIND.Other, '', '', None)

				fw.append(fw_info)
				# _log.debug("device %d firmware %s", devnumber, fw_info)
		return tuple(fw)
Example #23
0
def _get_clock():
    global _static_last_sec,_static_last_msec,_static_adjustment,_static_clock_seq
    sec,msec = _gettimeofday()
    try_again = True
    while try_again:
        try_again = False
        if _static_last_sec==0 and _static_last_msec==0:
            _static_clock_seq = _unpack(">H",_get_random_bytes(2))[0] & 0x1FFF
            _static_last_sec = sec - 1
            _static_last_msec = msec
        if sec < _static_last_sec or ((sec == _static_last_sec) and (msec < _static_last_msec)):
            _static_clock_seq = (_static_clock_seq+1) & 0x1FFF
            _static_adjustment = 0
            _static_last_sec = sec
            _static_last_msec = msec
        elif sec == _static_last_sec and msec == _static_last_msec:
            if _static_adjustment >= _MAX_ADJUSTMENT:
                try_again = True
            else:
                _static_adjustment += 1
        else:
            _static_adjustment = 0
            _static_last_sec = sec
            _static_last_msec = msec
    clock_reg = msec*10 + _static_adjustment
    clock_reg = (clock_reg + sec*10000000) & 0xFFFFFFFFFFFFFFFFL
    clock_reg = (clock_reg + (((0x01B21DD2L) << 32) + 0x13814000L)) & 0xFFFFFFFFFFFFFFFFL
    return (clock_reg >> 32),(clock_reg & 0xFFFFFFFFL),_static_clock_seq
Example #24
0
 def parsetag(self, data, curpos):
     '''Parse next tag from data string, starting at current position'''
     del self[:]
     itemlength = _unpack("<i",data[curpos:curpos+4])[0]
     if itemlength < 0:
         raise TagError, 'Corrupt tag, invalid item length at position ' \
                         '%i: %i bytes' % (curpos, itemlength)
     if data[curpos+4:curpos+7] != '\x00\x00\x00':
         raise TagError, 'Corrupt tag, invalid item flags, bits 8-31 ' \
                         'nonzero at position %i' % curpos
     type, readonly = divmod(ord(data[curpos+7]), 2)
     if type > 3:
         raise TagError, 'Corrupt tag, invalid item flags, bits 3-7 ' \
                         'nonzero at position %i' % curpos
     self.type = _apeitemtypes[type]
     self.readonly = bool(readonly)
     curpos += 8
     keyend = data.find("\x00", curpos)
     if keyend < curpos:
         raise TagError, 'Corrupt tag, unterminated item key at position ' \
                         '%i' % curpos
     itemkey = data[curpos:keyend]
     if not self.validkey(itemkey):
         raise TagError, 'Corrupt tag, invalid item key at position ' \
                         '%i: %r' % (curpos, itemkey)
     self.key = itemkey
     curpos = keyend + itemlength + 1
     itemvalue = data[keyend+1:curpos]
     if self.type == 'utf8' or self.type == 'external':
         self.extend(itemvalue.decode('utf8').split('\x00'))
     else:
         self.append(itemvalue)
     return curpos
    def _pkt_R(self):
        #
        # Startup Response
        #
        code = _unpack('!i', self.__read_bytes(4))[0]
        if code == 0:
            self.__authenticated = 1
            #print 'Authenticated!'
        elif code == 1:
            raise InterfaceError('Kerberos V4 authentication is required by server, but not supported by this client')
        elif code == 2:
            raise InterfaceError('Kerberos V5 authentication is required by server, but not supported by this client')
        elif code == 3:
            self.__send(_pack('!i', len(self.__passwd)+5) + self.__passwd + '\0')
        elif code == 4:
            salt = self.__read_bytes(2)
            try:
                import crypt
            except:
                raise InterfaceError('Encrypted authentication is required by server, but Python crypt module not available')
            cpwd = crypt.crypt(self.__passwd, salt)
            self.__send(_pack('!i', len(cpwd)+5) + cpwd + '\0')
        elif code == 5:
            import md5

            m = md5.new(self.__passwd + self.__userid).hexdigest()
            m = md5.new(m + self.__read_bytes(4)).hexdigest()
            m = 'md5' + m + '\0'
            self.__send(_pack('!i', len(m)+4) + m)
        else:
            raise InterfaceError('Unknown startup response code: R%d (unknown password encryption?)' % code)
Example #26
0
def decipher(v, k):
    """TEA 解密程序
    用128比特密钥, 解密64比特值
    """
    n = 16
    y, z = _unpack('>LL', v[0:8])
    a, b, c, d = _unpack('>LLLL', k[0:16])
    delta = 0x9E3779B9L
    s = (delta << 4) & op
    for i in xrange(n):
        z -= ((y << 4) + c) ^ (y + s) ^ ((y >> 5) + d)
        z &= op
        y -= ((z << 4) + a) ^ (z + s) ^ ((z >> 5) + b)
        y &= op
        s -= delta
        s &= op
    return _pack('>LL', y, z)
Example #27
0
def code(v, k):
    """TEA 加密
    64比特明码, 128比特密钥, qq的TEA算法使用16轮迭代
    """
    n = 16  #qq use 16
    delta = 0x9e3779b9L
    k = _unpack('>LLLL', k[0:16])
    y, z = _unpack('>LL', v[0:8])
    s = 0
    for i in xrange(n):
        s += delta
        y += (op & (z << 4)) + k[0] ^ z + s ^ (op & (z >> 5)) + k[1]
        y &= op
        z += (op & (y << 4)) + k[2] ^ y + s ^ (op & (y >> 5)) + k[3]
        z &= op
    r = _pack('>LL', y, z)
    return r
Example #28
0
    def lo_create(self, mode=INV_READ|INV_WRITE):
        """
        Return the oid of a new Large Object, created with the specified mode

        """
        if not self.__lo_funcs:
            self.__lo_init()
        r = self.funcall(self.__lo_funcs['lo_creat'], mode)
        return _unpack('!i', r)[0]
Example #29
0
    def lo_create(self, mode=INV_READ | INV_WRITE):
        """
        Return the oid of a new Large Object, created with the specified mode

        """
        if not self.__lo_funcs:
            self.__lo_init()
        r = self.funcall(self.__lo_funcs['lo_creat'], mode)
        return _unpack('!i', r)[0]
Example #30
0
def libuuid_generate_time():
    """Generate a UUID with libuuid by mixing time and MAC address.
    This will raise an exception if libuuid is not available.
    """
    buf = _pack(">16s","")
    out = _pack(">37s","")
    _libuuid.call("uuid_generate_time",buf)
    _libuuid.call("uuid_unparse",buf,out)
    return _unpack(">36sB",out)[0]
Example #31
0
def libuuid_generate_random():
    """Generate a UUID with libuuid using a high-quality source of randomness.
    This will raise an exception if libuuid is not available.
    """
    buf = _pack(">16s","")
    out = _pack(">37s","")
    _libuuid.call("uuid_generate_random",buf)
    _libuuid.call("uuid_unparse",buf,out)
    return _unpack(">36sB",out)[0]
Example #32
0
def libuuid_generate():
    """Generate a UUID with libuuid using the best available method.
    This will raise an exception if libuuid is not available.
    """
    buf = _pack(">16s","")
    out = _pack(">37s","")
    _libuuid.call("uuid_generate",buf)
    _libuuid.call("uuid_unparse",buf,out)
    return _unpack(">36sB",out)[0]
Example #33
0
def libuuid_generate_random():
    """Generate a UUID with libuuid using a high-quality source of randomness.
    This will raise an exception if libuuid is not available.
    """
    buf = _pack(">16s", "")
    out = _pack(">37s", "")
    _libuuid.call("uuid_generate_random", buf)
    _libuuid.call("uuid_unparse", buf, out)
    return _unpack(">36sB", out)[0]
Example #34
0
def libuuid_generate_time():
    """Generate a UUID with libuuid by mixing time and MAC address.
    This will raise an exception if libuuid is not available.
    """
    buf = _pack(">16s", "")
    out = _pack(">37s", "")
    _libuuid.call("uuid_generate_time", buf)
    _libuuid.call("uuid_unparse", buf, out)
    return _unpack(">36sB", out)[0]
Example #35
0
def libuuid_generate():
    """Generate a UUID with libuuid using the best available method.
    This will raise an exception if libuuid is not available.
    """
    buf = _pack(">16s", "")
    out = _pack(">37s", "")
    _libuuid.call("uuid_generate", buf)
    _libuuid.call("uuid_unparse", buf, out)
    return _unpack(">36sB", out)[0]
Example #36
0
def decipher(v, k):
    """
    TEA decipher, decrypt  64bits value with 128 bits key.
    TEA 解密程序, 用128比特密钥, 解密64比特值
    """
    n = 16
    y, z = _unpack('>LL', v[0:8]) 
    a, b, c, d = _unpack('>LLLL', k[0:16])
    delta = 0x9E3779B9L
    s = (delta << 4)&op 
    for i in xrange(n):
        z -= ((y << 4) + c) ^ (y + s) ^ ((y >> 5) + d)
        z &= op
        y -= ((z << 4) + a) ^ (z + s) ^ ((z >> 5) + b)
        y &= op
        s -= delta
        s &= op
    return _pack('>LL', y, z)
Example #37
0
    def encipher(self, v):
        """
		TEA coder encrypt 64 bits value, by 128 bits key,
		>>> c = encipher('abcdefgh', 'aaaabbbbccccdddd')
		>>> b2a_hex(c)
		'a557272c538d3e96'
		"""
        n = 16
        delta = 0x9e3779b9L
        k = _unpack('>LLLL', self.k[0:16])
        y, z = _unpack('>LL', v[0:8])
        s = 0
        for i in xrange(n):
            s += delta
            y += (op & (z << 4)) + k[0] ^ z + s ^ (op & (z >> 5)) + k[1]
            y &= op
            z += (op & (y << 4)) + k[2] ^ y + s ^ (op & (y >> 5)) + k[3]
            z &= op
        r = _pack('>LL', y, z)
        return r
Example #38
0
def inet_ntoa(packed_ip):
    """
    Convert an IP address from 32-bit packed binary format to string format.
    """
    if not _is_str(packed_ip):
        raise TypeError('string type expected, not %s' % str(type(packed_ip)))

    if len(packed_ip) != 4:
        raise ValueError('invalid length of packed IP address string')

    return '%d.%d.%d.%d' % _unpack('4B', packed_ip)
Example #39
0
def readBini(path):
    """
    read a bini-file and parse it into its abstract representation
    """
    with open(path, "rb") as f:
        if f.read(4) != b"BINI": raise Exception("Not a bini-file!")
        version, offset = _unpack("<ii", f.read(8))
        table = _readBinFile(path)[offset:]
        return version, [
            _parseSection(f, table) for i in _while(lambda: offset > f.tell())
        ]
Example #40
0
def inet_ntoa(packed_ip):
    """
    Convert an IP address from 32-bit packed binary format to string format.
    """
    if not hasattr(packed_ip, 'split'):
        raise TypeError('string type expected, not %s' % str(type(packed_ip)))

    if len(packed_ip) != 4:
        raise ValueError('invalid length of packed IP address string')

    return '%d.%d.%d.%d' % _unpack('4B', packed_ip)
Example #41
0
	def encipher(self, v):
		"""
		TEA coder encrypt 64 bits value, by 128 bits key,
		>>> c = encipher('abcdefgh', 'aaaabbbbccccdddd')
		>>> b2a_hex(c)
		'a557272c538d3e96'
		"""
		n = 16 
		delta = 0x9e3779b9L
		k = _unpack('>LLLL', self.k[0:16])
		y, z = _unpack('>LL', v[0:8])
		s = 0
		for i in xrange(n):
			s += delta
			y += (op &(z<<4))+ k[0] ^ z+ s ^ (op&(z>>5)) + k[1]
			y &= op
			z += (op &(y<<4))+ k[2] ^ y+ s ^ (op&(y>>5)) + k[3]
			z &= op
		r = _pack('>LL',y,z)
		return r
Example #42
0
 def read_data(self, data) -> None:
     """
     Read the ID and length of a packet.
     (increments the offset accordingly)
     """
     self.data = data
     size: int = calcsize('<hh')
     self.id, self.length = _unpack(
         '<hh', self.data[self.offset:self.offset + size])
     self.offset += size
     del size
     return
Example #43
0
def get_battery(device):
	"""Reads a device's battery level.

	:raises FeatureNotSupported: if the device does not support this feature.
	"""
	battery = feature_request(device, FEATURE.BATTERY)
	if battery:
		discharge, dischargeNext, status = _unpack(b'!BBB', battery[:3])
		if _log.isEnabledFor(_DEBUG):
			_log.debug("device %d battery %d%% charged, next level %d%% charge, status %d = %s",
						device.number, discharge, dischargeNext, status, BATTERY_STATUS[status])
		return discharge, BATTERY_STATUS[status]
Example #44
0
    def _pkt_T(self):
        #
        # Row Description
        #
        nFields = _unpack('!h', self.__read_bytes(2))[0]
        descr = []
        for i in range(nFields):
            fieldname = self.__read_string()
            oid, type_size, type_modifier = _unpack('!ihi', self.__read_bytes(10))
            descr.append((fieldname, oid, type_size, type_modifier))

        description = []
        for name, oid, size, modifier in descr:
            pg_type = self._oid_map.get(oid, _DEFAULT_PGTYPE)
            description.append((name, pg_type.type_id, None, None, None, None, None))

        # Save the field description list
        self.__current_result.set_description(description)

        # build a list of field conversion functions we can use against each row
        self.__current_result.conversion = [self._get_conversion(d[1]) for d in descr]
Example #45
0
def code(v, k):
    """
    TEA coder encrypt 64 bits value, by 128 bits key,
    QQ do 16 round TEA.

    >>> c = code('abcdefgh', 'aaaabbbbccccdddd')
    >>> b2a_hex(c)
    'a557272c538d3e96'
    """
    n = 16  #qq use 16
    delta = 0x9e3779b9L
    k = _unpack('>LLLL', k[0:16])
    y, z = _unpack('>LL', v[0:8])
    s = 0
    for i in xrange(n):
        s += delta
        y += (op & (z << 4)) + k[0] ^ z + s ^ (op & (z >> 5)) + k[1]
        y &= op
        z += (op & (y << 4)) + k[2] ^ y + s ^ (op & (y >> 5)) + k[3]
        z &= op
    r = _pack('>LL', y, z)
    return r
Example #46
0
 def _get_header(self):
     header = _unpack(self._endian + self.HEADER_TYPE,
                      self.fhandle.read(self.HEADER_SIZE))
     self.header = {}
     index = 0
     for field, nchunks in zip(self.HEADER_FIELDS, self.HEADER_CHUNKS):
         end = index + nchunks
         if nchunks > 1:
             self.header[field] = header[index: end]
         else:
             self.header[field] = header[index]
         index = end
     self.header['label'] = ''.join(self.header['label'])
Example #47
0
    def lo_open(self, oid, mode=INV_READ|INV_WRITE):
        """
        Open the Large Object with the specified oid, returns
        a file-like object

        """
        if not self.__lo_funcs:
            self.__lo_init()
        r = self.funcall(self.__lo_funcs['lo_open'], oid, mode)
        fd = _unpack('!i', r)[0]
        lobj =  _LargeObject(self, fd)
        lobj.seek(0, SEEK_SET)
        return lobj
Example #48
0
 def _get_header(self):
     header = _unpack(self._endian + self.HEADER_TYPE,
                      self.fhandle.read(self.HEADER_SIZE))
     self.header = {}
     index = 0
     for field, nchunks in zip(self.HEADER_FIELDS, self.HEADER_CHUNKS):
         end = index + nchunks
         if nchunks > 1:
             self.header[field] = header[index:end]
         else:
             self.header[field] = header[index]
         index = end
     self.header['label'] = ''.join(self.header['label'])
Example #49
0
    def lo_open(self, oid, mode=INV_READ | INV_WRITE):
        """
        Open the Large Object with the specified oid, returns
        a file-like object

        """
        if not self.__lo_funcs:
            self.__lo_init()
        r = self.funcall(self.__lo_funcs['lo_open'], oid, mode)
        fd = _unpack('!i', r)[0]
        lobj = _LargeObject(self, fd)
        lobj.seek(0, SEEK_SET)
        return lobj
Example #50
0
    def decipher(self, v):
        """
		TEA decipher, decrypt  64bits value with 128 bits key.

		it's the inverse function of TEA encrypt.

		>>> c = encipher('abcdefgh', 'aaaabbbbccccdddd')
		>>> decipher( c, 'aaaabbbbccccdddd')
		'abcdefgh'
		"""
        n = 16
        y, z = _unpack('>LL', v[0:8])
        a, b, c, d = _unpack('>LLLL', self.k[0:16])
        delta = 0x9E3779B9L
        s = (delta << 4) & op
        for i in xrange(n):
            z -= ((y << 4) + c) ^ (y + s) ^ ((y >> 5) + d)
            z &= op
            y -= ((z << 4) + a) ^ (z + s) ^ ((z >> 5) + b)
            y &= op
            s -= delta
            s &= op
        return _pack('>LL', y, z)
Example #51
0
 def _pkt_V(self):
     #
     # Function call response
     #
     self.__func_result = None
     while 1:
         ch = self.__read_bytes(1)
         if ch == "0":
             break
         if ch == "G":
             result_size = _unpack("!i", self.__read_bytes(4))[0]
             self.__func_result = self.__read_bytes(result_size)
         else:
             raise InterfaceError("Unexpected byte: [%s] in Function call reponse" % ch)
 def _pkt_V(self):
     #
     # Function call response
     #
     self.__func_result = None
     while 1:
         ch = self.__read_bytes(1)
         if ch == '0':
             break
         if ch == 'G':
             result_size = _unpack('!i', self.__read_bytes(4))[0]
             self.__func_result = self.__read_bytes(result_size)
         else:
             raise InterfaceError('Unexpected byte: [%s] in Function call reponse' % ch)
Example #53
0
 def _pkt_V(self):
     #
     # Function call response
     #
     self.__func_result = None
     while True:
         ch = self.__read_bytes(1)
         if ch == '0':
             break
         if ch == 'G':
             result_size = _unpack('!i', self.__read_bytes(4))[0]
             self.__func_result = self.__read_bytes(result_size)
         else:
             raise InterfaceError('Unexpected byte: [%s] in Function call reponse' % ch)
Example #54
0
	def decipher(self, v):
		"""
		TEA decipher, decrypt  64bits value with 128 bits key.

		it's the inverse function of TEA encrypt.

		>>> c = encipher('abcdefgh', 'aaaabbbbccccdddd')
		>>> decipher( c, 'aaaabbbbccccdddd')
		'abcdefgh'
		"""
		n = 16
		y, z = _unpack('>LL', v[0:8])
		a, b, c, d = _unpack('>LLLL', self.k[0:16])
		delta = 0x9E3779B9L;
		s = (delta << 4)&op
		for i in xrange(n):
			z -= ((y<<4)+c) ^ (y+s) ^ ((y>>5) + d)
			z &= op
			y -= ((z<<4)+a) ^ (z+s) ^ ((z>>5) + b)
			y &= op
			s -= delta
			s &= op
		return _pack('>LL', y, z)
Example #55
0
 def _load_shd(self, fname_base):
     with open(fname_base + '.shd', 'rb') as f:
         recl, = _unpack('i', f.read(4))
         title = str(f.read(80))
         f.seek(4 * recl, 0)
         ptype = f.read(10).decode('utf8').strip()
         assert ptype == 'rectilin', 'Invalid file format (expecting ptype == "rectilin")'
         f.seek(8 * recl, 0)
         nfreq, ntheta, nsx, nsy, nsd, nrd, nrr, atten = _unpack(
             'iiiiiiif', f.read(32))
         assert nfreq == 1, 'Invalid file format (expecting nfreq == 1)'
         assert ntheta == 1, 'Invalid file format (expecting ntheta == 1)'
         assert nsd == 1, 'Invalid file format (expecting nsd == 1)'
         f.seek(32 * recl, 0)
         pos_r_depth = _unpack('f' * nrd, f.read(4 * nrd))
         f.seek(36 * recl, 0)
         pos_r_range = _unpack('f' * nrr, f.read(4 * nrr))
         pressure = _np.zeros((nrd, nrr), dtype=_np.complex)
         for ird in range(nrd):
             recnum = 10 + ird
             f.seek(recnum * 4 * recl, 0)
             temp = _np.array(_unpack('f' * 2 * nrr, f.read(2 * nrr * 4)))
             pressure[ird, :] = temp[::2] + 1j * temp[1::2]
     return _pd.DataFrame(pressure, index=pos_r_depth, columns=pos_r_range)
Example #56
0
	def __getitem__(self, index):
		if isinstance(index, int):
			if index < 0 or index >= len(self.keys):
				raise IndexError(index)

			if self.keys[index] is None:
				keydata = feature_request(self.device, FEATURE.REPROGRAMMABLE_KEYS, 0x10, index)
				if keydata:
					key, key_task, flags = _unpack(b'!HHB', keydata[:5])
					self.keys[index] = _ReprogrammableKeyInfo(index, KEY[key], KEY[key_task], flags)

			return self.keys[index]

		elif isinstance(index, slice):
			indices = index.indices(len(self.keys))
			return [self.__getitem__(i) for i in range(*indices)]
Example #57
0
	def __getitem__(self, index):
		if self._check():
			if isinstance(index, int):
				if index < 0 or index >= len(self.features):
					raise IndexError(index)

				if self.features[index] is None:
					feature = self.device.feature_request(FEATURE.FEATURE_SET, 0x10, index)
					if feature:
						feature, = _unpack(b'!H', feature[:2])
						self.features[index] = FEATURE[feature]

				return self.features[index]

			elif isinstance(index, slice):
				indices = index.indices(len(self.features))
				return [self.__getitem__(i) for i in range(*indices)]
Example #58
0
	def __read_row(self, ascii=True):
		#
		# Read an ASCII or Binary Row
		#
		result = self.__current_result
		
		# check if we need to use longs (more than 32 fields)
		if result.null_byte_count > 4:
			null_bits = 0
			field_mask = 128
		else:
			null_bits = 0
			field_mask = 128
		
		# read bytes holding null bits and setup the field mask
		# to point at the first (leftmost) field
		if result.null_byte_count:
			for ch in self.__read_bytes(result.null_byte_count):
				# null_bits = (null_bits << 8) | ord(ch)
				null_bits = (null_bits << 8) | ch
			field_mask <<= (result.null_byte_count - 1) * 8
		
		# read each field into a row
		row = []
		for field_num in range(result.num_fields):
			if null_bits & field_mask:
				# field has data present, read what was sent
				field_size = _unpack('!i', self.__read_bytes(4))[0]
				if ascii:
					field_size -= 4
				data = self.__read_bytes(field_size)
				# XYZ
				row.append(result.conversion[field_num](data))
			else:
				# field has no data (is null)
				row.append(None)
			field_mask >>= 1

		result.rows.append(row)
Example #59
0
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied.
# See the Licence for the specific language governing
# permissions and limitations under the Licence.
# -----------------------------------------------------------------------------

import logging
log = logging.getLogger(__name__)

import sys, time
from binascii import hexlify
if sys.hexversion >= 0x020704F0:
    from struct import pack, unpack
else: # for Debian Wheezy (and thus Raspbian)
    from struct import pack, unpack as _unpack
    unpack = lambda fmt, string: _unpack(fmt, buffer(string))

from nfc.tag import Tag, TagCommandError
import nfc.clf

def hexdump(octets, sep=""):
    return sep.join(("??" if x is None else ("%02x" % x)) for x in octets)

def chrdump(octets, sep=""):
    return sep.join(("{:c}".format(x) if 32<=x<=126 else ".") for x in octets)

def pagedump(page, octets, info=None):
    info = ("|%s|" % chrdump(octets)) if info is None else ("(%s)" % info)
    page = "  * " if page is None else "{0:03X}:".format(page)
    return "{0} {1} {2}".format(page, hexdump(octets, sep=" "), info)