Python源码示例:binascii.hexlify()

示例1
def render(self):
        while self.ts.run:
            while self.ts.pause:
                self.checkkey()
                time.sleep(.1)

            (self.maxy,self.maxx) = self.stdscr.getmaxyx()

            self.sx = 1
            self.sy = max((self.maxy + 1 - (self.T.IL + self.T.UL + 5 + 2))/2, 0)

            self.checkkey()

            synth_insn = cstr2py(self.T.r.raw_insn)

            if synth_insn and not self.ts.pause:
                self.draw()

            if self.do_tick:
                self.ticks = self.ticks + 1
                if self.ticks & self.TICK_MASK == 0:
                    with open(TICK, 'w') as f:
                        f.write("%s" % hexlify(synth_insn))

            time.sleep(self.TIME_SLICE) 
示例2
def get(self, file_id: str) -> None:  # type: ignore
        """Get a file from the database and show it in hex."""

        with database.session() as session:
            file = (
                session.query(database.File)
                .filter(database.File.slug == file_id)
                .first()
            )

            if not file:
                raise tornado.web.HTTPError(404)

            if file.paste.exp_date < datetime.now():
                session.delete(file.paste)
                session.commit()

                log.warn(
                    "FileRaw.get: paste was expired, is your cronjob running?"
                )

                raise tornado.web.HTTPError(404)

            self.set_header("Content-Type", "text/plain; charset=utf-8")
            self.write(binascii.hexlify(file.raw.encode("latin1"))) 
示例3
def message(self):
        error_details_msg = ""
        for error_detail in self.error_details:
            if isinstance(error_detail, SMB2SymbolicLinkErrorResponse):
                detail_msg = self._get_symlink_error_detail_msg(error_detail)
            elif isinstance(error_detail, SMB2ShareRedirectErrorContext):
                detail_msg = self._get_share_redirect_detail_msg(error_detail)
            else:
                # unknown error details in response, output raw bytes
                detail_msg = "Raw: %s" % binascii.hexlify(error_detail).decode('utf-8')

            # the first details message is set differently
            if error_details_msg == "":
                error_details_msg = "%s - %s" % (error_details_msg, detail_msg)
            else:
                error_details_msg = "%s, %s" % (error_details_msg, detail_msg)

        status_hex = format(self.status, 'x')
        error_message = "%s: 0x%s%s" % (str(self.header['status']),
                                        status_hex, error_details_msg)
        return "Received unexpected status from the server: %s" % error_message 
示例4
def switchfets(port='/dev/ttyUSB0'):
  """ switch charge and discharge fets """
  print ('(03)=Both FETs off')
  print ('(01)=Discharge FET on, Charge FET off')
  print ('(02)=Discharge FET off, Charge FET on')
  print ('(00)=Both FETs on')
  usercmd = input("Enter numeric option> ")
  ser = bmscore.openbms(port)
  command = bytes.fromhex('DD A5 03 00 FF FD 77')
  print ('command=',binascii.hexlify(command))
  data=bmscore.getbmsdat(ser,command)
  print ('reply=',binascii.hexlify(data))
  command = bytes.fromhex('DD A5 04 00 FF FC 77')
  print ('command=',binascii.hexlify(command))
  data=bmscore.getbmsdat(ser,command)
  print ('reply=',binascii.hexlify(data))
  command = bytes.fromhex('DD 5A 00 02 56 78 FF 30 77')
  data=bmscore.getbmsdat(ser,command)
  print ('reply=',binascii.hexlify(data))
  usercmd=b'\xE1\x02\x00'+bytes.fromhex(usercmd)
  command = b'\xDD\x5A'+usercmd+bmscore.crccalc(usercmd).to_bytes(2, byteorder='big')+b'\x77'
  print (binascii.hexlify(command))
  bmscore.getbmsdat(ser,command)
  command = bytes.fromhex('DD 5A 01 02 00 00 FF FD 77')
  bmscore.getbmsdat(ser,command) 
示例5
def getbmsdat(port,command):
  """ Issue BMS command and return data as byte data """
  """ assumes data port is open and configured """
  print ('command=',binascii.hexlify(command))
  port.write(command)
  reply = port.read(4)
  x = int.from_bytes(reply[3:5], byteorder = 'big')
  data = port.read(x)
  end = port.read(3)
  if len(data)<x:
    print ('Serial Timeout')
  if crccalc(reply[2:4]+data)!=int.from_bytes(end[0:2],byteorder ='big') and x!=0:
    print('CRC Error')
  print ('reply=',binascii.hexlify(data))
  return data 
示例6
def x(self):
    """ Get data from BMS board"""
    command = bytes.fromhex('DD A5 03 00 FF FD 77')
    dat = self.getbmsdat(self.ser,command)
    self.rawi[0] = int.from_bytes(dat[2:4], byteorder = 'big',signed=True)
#    print (self.rawi)
#    self.line1 = [ 0 for i in range(int(len(dat)))]
#    for i in range(0,int(len(dat))):
  #    print (dat[i*2:i*2+2])
  #    print (int.from_bytes(dat[i:i+1], byteorder = 'big'))
#      self.line1[i] = int.from_bytes(dat[i:i+1], byteorder = 'big')
#    print (binascii.hexlify(dat))
#    print (self.line1)


  # voltages
    command = bytes.fromhex('DD A5 04 00 FF FC 77')
    voltages = self.getbmsdat(self.ser,command)
    for i in range(0,numcells):
      self.rawv[i+1] = int.from_bytes(voltages[i*2:i*2+2], byteorder = 'big')\
                       /1000.00
      self.rawv[i+1] = self.rawv[i+1]+self.rawv[i]
  #  print (self.rawv)
  #  print (binascii.hexlify(voltages)) 
示例7
def _bytes_representation(data):
    """
    Converts a bytestring into something that is safe to print on all Python
    platforms.

    This function is relatively expensive, so it should not be called on the
    mainline of the code. It's safe to use in things like object repr methods
    though.
    """
    if data is None:
        return None

    hex = binascii.hexlify(data)

    # This is moderately clever: on all Python versions hexlify returns a byte
    # string. On Python 3 we want an actual string, so we just check whether
    # that's what we have.
    if not isinstance(hex, str):  # pragma: no cover
        hex = hex.decode('ascii')

    return hex 
示例8
def assert_fingerprint(cert, fingerprint):
    """
    Checks if given fingerprint matches the supplied certificate.

    :param cert:
        Certificate as bytes object.
    :param fingerprint:
        Fingerprint as string of hexdigits, can be interspersed by colons.
    """

    fingerprint = fingerprint.replace(':', '').lower()
    digest_length = len(fingerprint)
    hashfunc = HASHFUNC_MAP.get(digest_length)
    if not hashfunc:
        raise SSLError(
            'Fingerprint of invalid length: {0}'.format(fingerprint))

    # We need encode() here for py32; works on py2 and p33.
    fingerprint_bytes = unhexlify(fingerprint.encode())

    cert_digest = hashfunc(cert).digest()

    if not _const_compare_digest(cert_digest, fingerprint_bytes):
        raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'
                       .format(fingerprint, hexlify(cert_digest))) 
示例9
def with_payment_id(self, payment_id=0):
        """Integrates payment id into the address.

        :param payment_id: int, hexadecimal string or :class:`PaymentID <monero.numbers.PaymentID>`
                    (max 64-bit long)

        :rtype: `IntegratedAddress`
        :raises: `TypeError` if the payment id is too long
        """
        payment_id = numbers.PaymentID(payment_id)
        if not payment_id.is_short():
            raise TypeError("Payment ID {0} has more than 64 bits and cannot be integrated".format(payment_id))
        prefix = const.INTADDRR_NETBYTES[const.NETS.index(self.net)]
        data = bytearray([prefix]) + self._decoded[1:65] + struct.pack('>Q', int(payment_id))
        checksum = bytearray(keccak_256(data).digest()[:4])
        return IntegratedAddress(base58.encode(hexlify(data + checksum))) 
示例10
def get_md5_hash(self, enc_hex, key):
        # convert hash from hex to binary
        enc_binary = binascii.unhexlify(enc_hex)

        # retrieve the salt
        salt = hashlib.sha1('\x00\x00\x00\x00' + key).digest() + hashlib.sha1('\x00\x00\x00\x01' + key).digest()

        # encrypt value used with the XOR operation
        aes_key = self.aes_encrypt(struct.pack('I', 0) * 4, salt[0:32])[0:16]

        # XOR operation
        decrypted = []
        for d in range(16):
            decrypted.append(struct.unpack('B', enc_binary[d])[0] ^ struct.unpack('B', aes_key[d])[0])

        # cast the result byte
        tmp = ''
        for dec in decrypted:
            tmp = tmp + struct.pack(">I", dec).strip('\x00')

        # byte to hex
        return binascii.hexlify(tmp)

    # used for dictionary attack, if user specify a specific file 
示例11
def _dump_additional_attributes(additional_attributes):
    """ try to parse additional attributes, but ends up to hexdump if the scheme is unknown """

    attributes_raw = io.BytesIO(additional_attributes)
    attributes_hex = binascii.hexlify(additional_attributes)

    if not len(additional_attributes):
        return attributes_hex

    len_attribute, = unpack('<I', attributes_raw.read(4))
    if len_attribute != 8:
        return attributes_hex

    attr_id, = unpack('<I', attributes_raw.read(4))
    if attr_id != APK._APK_SIG_ATTR_V2_STRIPPING_PROTECTION:
        return attributes_hex
        
    scheme_id, = unpack('<I', attributes_raw.read(4))

    return "stripping protection set, scheme %d" % scheme_id 
示例12
def get_distrust_timeline(
        cls, verified_certificate_chain: List[Certificate]
    ) -> Optional[SymantecDistrustTimelineEnum]:
        has_whitelisted_cert = False
        has_blacklisted_cert = False

        # Is there a Symantec root certificate in the chain?
        for certificate in verified_certificate_chain:
            key_hash = binascii.hexlify(get_public_key_sha256(certificate)).decode("ascii")
            if key_hash in cls._CA_KEYS_BLACKLIST:
                has_blacklisted_cert = True
            if key_hash in cls._CA_KEYS_WHITELIST:
                has_whitelisted_cert = True

        distrust_enum = None
        if has_blacklisted_cert and not has_whitelisted_cert:
            leaf_cert = verified_certificate_chain[0]
            if leaf_cert.not_valid_before < datetime(year=2016, month=6, day=1):
                distrust_enum = SymantecDistrustTimelineEnum.MARCH_2018
            else:
                distrust_enum = SymantecDistrustTimelineEnum.SEPTEMBER_2018
        return distrust_enum 
示例13
def _convert_hexstring(input_spec,
                       output_spec,
                       output_codec,
                       type_name,
                       hexstring):
    try:
        encoded = binascii.unhexlify(hexstring)
    except Exception as e:
        raise TypeError("'{}': {}".format(hexstring, str(e)))

    decoded = input_spec.decode(type_name, encoded)

    if output_codec in ['gser', 'xer', 'jer']:
        decoded = output_spec.encode(type_name, decoded, indent=4).strip()
    else:
        decoded = binascii.hexlify(output_spec.encode(type_name, decoded))

    print(decoded.decode('latin-1')) 
示例14
def key_fingerprint(key):
    hex_fp = binascii.hexlify(key.get_fingerprint()).decode()
    return key.get_name() + " " + ":".join(hex_fp[i:i + 2] for i in range(0, len(hex_fp), 2)) 
示例15
def __str__(self):
        return hexlify(self.token) 
示例16
def _function_get_json(func):
    """Return the function in standalone JSON"""
    data = dict(func.data)
    data["chunks"] = []
    for chunk in func.chunks:
        c = dict(chunk.data)
        c["bytes"] = binascii.hexlify(chunk.bytes)
        data["chunks"].append(c)

    return data 
示例17
def wildcard_instruction(addr):
    """Replaces bytes related to memory addresses with wildcards.

    Args:
      addr: the address of the current instruction to be wildcarded

    Returns:
      String: hex-encoded representation of the bytes obtained at addr where
              all the operands that refers to memmory addresses are wildcarded.
    """

    pattern = ''
    mask = ida_idp.ph_calcrel(addr)
    mask_str = binascii.hexlify(mask).decode('utf-8')

    logging.debug(
        '[VTGREP] Wildcarding: %s',
        idc.generate_disasm_line(addr, 0)
        )

    current_byte = 0
    index_instr = 0
    pattern = ' '

    while current_byte < len(mask_str):
      if mask_str[current_byte] != '0' or mask_str[current_byte+1] != '0':
        pattern += '?? '
      else:
        instr_bytes = idc.get_bytes(addr+index_instr, 1)
        pattern += binascii.hexlify(instr_bytes).decode('utf-8') + ' '
      current_byte += 2
      index_instr += 1

    logging.debug('[VTGREP] Wildcarded: %s', pattern)

    return pattern 
示例18
def generate_id(self):
        """Return a new session id."""
        return binascii.hexlify(os.urandom(20)).decode('ascii') 
示例19
def result_string(insn, result):
    s = "%30s %2d %2d %2d %2d (%s)\n" % (
            hexlify(insn), result.valid,
            result.length, result.signum,
            result.sicode, hexlify(cstr2py(result.raw_insn)))
    return s 
示例20
def cleanup(gui, poll, injector, ts, tests, command_line, args):
    ts.run = False
    if gui:
        gui.stop()
    if poll:
        poll.stop()
    if injector:
        injector.stop()

    '''
    # doesn't work
    if gui:
        for (i, c) in enumerate(gui.orig_colors):
            curses.init_color(i, c[0], c[1], c[2])
    '''

    curses.nocbreak();
    curses.echo()
    curses.endwin()

    dump_artifacts(tests, injector, command_line)

    if args.save:
        with open(LAST, "w") as f:
            f.write(hexlify(cstr2py(tests.r.raw_insn)))

    sys.exit(0) 
示例21
def mac_string(device_id):
    """
    Converts a device id into a mac address hex string

    :param device_id: The device id
    :returns: str -- The mac address represented as a string
    """
    return hexlify(byteswap('6', pack('u48', device_id))) 
示例22
def test_pack_section(self):
        for pack_type, args, packet in PACK_TEST_CASES:
            self.assertEqual(hexlify(lifx.protocol.pack_section(pack_type, *args)), packet) 
示例23
def test_make_packet(self):
        for kwargs, args, packet, vals in EXAMPLE_PACKETS:
            self.assertEqual(hexlify(lifx.protocol.make_packet(*args, **kwargs)), packet) 
示例24
def test_discovery_packet(self):
        self.assertEqual(
                hexlify(lifx.protocol.discovery_packet(23, 5)),
                '240000341700000000000000000000000000000000000105000000000000000002000000',
        ) 
示例25
def get_ipaddress(self):
        # get's the IP address in a human readable format
        ip_address = self['ip_address'].get_value()
        if self['type'].get_value() == IpAddrType.MOVE_DST_IPADDR_V4:
            return socket.inet_ntoa(ip_address)
        else:
            addr = binascii.hexlify(ip_address).decode('utf-8')
            return ":".join([addr[i:i + 4] for i in range(0, len(addr), 4)]) 
示例26
def verify_signature(self, header, session_id, force=False):
        """
        Verifies the SMB2 Header request/response signature.

        :param header: The SMB2Header that will have its signature verified against the signing key specified.
        :param session_id: The Session Id to denote what session security verifies the message.
        :param force: Force verification of the header even if it does not match the criteria required in normal
            scenarios.
        """
        message_id = header['message_id'].get_value()
        flags = header['flags']
        status = header['status'].get_value()
        command = header['command'].get_value()

        if not force and (message_id == 0xFFFFFFFFFFFFFFFF or
                          not flags.has_flag(Smb2Flags.SMB2_FLAGS_SIGNED) or
                          status == NtStatus.STATUS_PENDING or
                          command == Commands.SMB2_SESSION_SETUP):
            return

        session = self.session_table.get(session_id, None)
        if session is None:
            raise SMBException("Failed to find session %s for message verification" % session_id)

        expected = self._generate_signature(header.pack(), session.signing_key)
        actual = header['signature'].get_value()
        if actual != expected:
            raise SMBException("Server message signature could not be verified: %s != %s"
                               % (to_native(binascii.hexlify(actual)), to_native(binascii.hexlify(expected)))) 
示例27
def get_ipaddress(self):
        # get's the full IPv6 Address, note this is the full address and has
        # not been concatenated
        addr_bytes = self['ipv6_address'].get_value()
        address = binascii.hexlify(addr_bytes).decode('utf-8')
        return ":".join([address[i:i + 4] for i in range(0, len(address), 4)]) 
示例28
def _hex(str_or_bytes):
    # PY2: _hex('北京') --> 'e58c97e4baac'
    # PY3: _hex('北京') --> b'e58c97e4baac'
    if PY2:
        hex_str = hexlify(str_or_bytes)
    else:
        # python3
        if isinstance(str_or_bytes, text_type):
            byte = str_or_bytes.encode(encoding=E_FMT)
        elif isinstance(str_or_bytes, binary_type):
            byte = str_or_bytes
        else:
            byte = b''
        hex_str = hexlify(byte)
    return hex_str 
示例29
def hashToken(self,token):
        return hexlify(pbkdf2_hmac('sha256',token, sha1('CBoePassword').digest(), 100000)) 
示例30
def ntlm(password):
    hashval = hashlib.new('md4', password.encode('utf-16le')).digest()
    return hexlify(hashval)