python类hexlify()的实例源码

ssl_.py 文件源码 项目:jira_worklog_scanner 作者: pgarneau 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)))
rfcat_receiver.py 文件源码 项目:iSmartAlarm 作者: seekintoo 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def main():

        try:
            if len(sys.argv) != 2:
                print "Usage   : %s 908000000" % sys.argv[0]
                sys.exit(0)

        d = RfCat()
        ConfigureD(d, long(sys.argv[1]))
        d.setModeRX() 

        while True:
        pkt   = d.RFrecv(timeout=120000)
        frame = hexlify(pkt[0])
                print "[rfcat recv] : '%s'\n" % (frame)

        except KeyboardInterrupt, e:
            print("W: interrupt received, proceeding")
            print e

        finally:
        d.setModeIDLE()
        sys.exit(0)
ssl_.py 文件源码 项目:workflows.kyoyue 作者: wizyoung 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)))
microphone.py 文件源码 项目:pi-topPULSE 作者: pi-top 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _space_separated_little_endian(integer_value, byte_len):
    """INTERNAL. Get an integer in format for WAV file header."""

    if byte_len <= 1:
        pack_type = '<B'
    elif byte_len <= 2:
        pack_type = '<H'
    elif byte_len <= 4:
        pack_type = '<I'
    elif byte_len <= 8:
        pack_type = '<Q'
    else:
        PTLogger.info("Value cannot be represented in 8 bytes - exiting")
        exit()

    hex_string = pack(pack_type, integer_value)
    temp = hexlify(hex_string).decode()
    return ' '.join([temp[i:i + 2] for i in range(0, len(temp), 2)])
hashers.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def encode(self, password, salt):
        bcrypt = self._load_library()
        # Need to reevaluate the force_bytes call once bcrypt is supported on
        # Python 3

        # Hash the password prior to using bcrypt to prevent password truncation
        #   See: https://code.djangoproject.com/ticket/20138
        if self.digest is not None:
            # We use binascii.hexlify here because Python3 decided that a hex encoded
            #   bytestring is somehow a unicode.
            password = binascii.hexlify(self.digest(force_bytes(password)).digest())
        else:
            password = force_bytes(password)

        data = bcrypt.hashpw(password, salt)
        return "%s$%s" % (self.algorithm, force_text(data))
ssl_.py 文件源码 项目:zanph 作者: zanph 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)))
ssl_.py 文件源码 项目:zanph 作者: zanph 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)))
reversename.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def from_address(text):
    """Convert an IPv4 or IPv6 address in textual form into a Name object whose
    value is the reverse-map domain name of the address.
    @param text: an IPv4 or IPv6 address in textual form (e.g. '127.0.0.1',
    '::1')
    @type text: str
    @rtype: dns.name.Name object
    """
    try:
        v6 = dns.ipv6.inet_aton(text)
        if dns.ipv6.is_mapped(v6):
            if sys.version_info >= (3,):
                parts = ['%d' % byte for byte in v6[12:]]
            else:
                parts = ['%d' % ord(byte) for byte in v6[12:]]
            origin = ipv4_reverse_domain
        else:
            parts = [x for x in str(binascii.hexlify(v6).decode())]
            origin = ipv6_reverse_domain
    except:
        parts = ['%d' %
                 byte for byte in bytearray(dns.ipv4.inet_aton(text))]
        origin = ipv4_reverse_domain
    parts.reverse()
    return dns.name.from_text('.'.join(parts), origin=origin)
ssl_.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)))
random.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def seed(self, a=None):
        """Initialize internal state from hashable object.

        None or no argument seeds from current time or from an operating
        system specific randomness source if available.

        If a is not None or an int or long, hash(a) is used instead.
        """

        if a is None:
            try:
                # Seed with enough bytes to span the 19937 bit
                # state space for the Mersenne Twister
                a = long(_hexlify(_urandom(2500)), 16)
            except NotImplementedError:
                import time
                a = long(time.time() * 256) # use fractional seconds

        super(Random, self).seed(a)
        self.gauss_next = None
ssl_.py 文件源码 项目:YoWhenReady 作者: jnsdrtlf 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)))
Bella.py 文件源码 项目:Bella 作者: Trietptm-on-Security 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def kciCloudHelper(iCloudKey):
    #this function is tailored to keychaindump. Takes an iCloud key, and returns tokens
    msg = base64.b64decode(iCloudKey)
    key = "t9s\"lx^awe.580Gj%'ld+0LG<#9xa?>vb)-fkwb92[}"
    hashed = hmac.new(key, msg, digestmod=hashlib.md5).digest()
    hexedKey = binascii.hexlify(hashed)
    IV = 16 * '0'
    mme_token_file = glob("/Users/%s/Library/Application Support/iCloud/Accounts/*" % get_bella_user()) #this doesnt need to be globber bc only current user's info can be decrypted
    for x in mme_token_file:
        try:
            int(x.split("/")[-1])
            mme_token_file = x
        except ValueError:
            continue
    send_msg("\t%sDecrypting token plist\n\t    [%s]\n" % (blue_star, mme_token_file), False)
    decryptedBinary = subprocess.check_output("openssl enc -d -aes-128-cbc -iv '%s' -K %s < '%s'" % (IV, hexedKey, mme_token_file), shell=True)
    from Foundation import NSData, NSPropertyListSerialization
    binToPlist = NSData.dataWithBytes_length_(decryptedBinary, len(decryptedBinary))
    token_plist = NSPropertyListSerialization.propertyListWithData_options_format_error_(binToPlist, 0, None, None)[0]
    tokz = "[%s | %s]\n" % (token_plist["appleAccountInfo"]["primaryEmail"], token_plist["appleAccountInfo"]["fullName"])
    tokz += "%s:%s\n" % (token_plist["appleAccountInfo"]["dsPrsID"], token_plist["tokens"]["mmeAuthToken"])
    return tokz
wltrace.py 文件源码 项目:wltrace 作者: jhshi 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def load_trace(path, *args, **kwargs):
    """Read a packet trace file, return a :class:`wltrace.common.WlTrace` object.

    This function first reads the file's magic
    (first ``FILE_TYPE_HANDLER`` bytes), and automatically determine the
    file type, and call appropriate handler to process the file.

    Args:
        path (str): the file's path to be loaded.

    Returns:
        ``WlTrace`` object.
    """
    with open(path, 'rb') as f:
        magic = f.read(MAGIC_LEN)
    if magic not in FILE_TYPE_HANDLER:
        raise Exception('Unknown file magic: %s' % (binascii.hexlify(magic)))

    return FILE_TYPE_HANDLER[magic](path, *args, **kwargs)
win32.py 文件源码 项目:GAMADV-XTD 作者: taers232c 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def raw_lmhash(secret, encoding="ascii", hex=False):
    """encode password using des-based LMHASH algorithm; returns string of raw bytes, or unicode hex"""
    # NOTE: various references say LMHASH uses the OEM codepage of the host
    #       for its encoding. until a clear reference is found,
    #       as well as a path for getting the encoding,
    #       letting this default to "ascii" to prevent incorrect hashes
    #       from being made w/o user explicitly choosing an encoding.
    if isinstance(secret, unicode):
        secret = secret.encode(encoding)
    ns = secret.upper()[:14] + b"\x00" * (14-len(secret))
    out = des_encrypt_block(ns[:7], LM_MAGIC) + des_encrypt_block(ns[7:], LM_MAGIC)
    return hexlify(out).decode("ascii") if hex else out

#=============================================================================
# eoc
#=============================================================================
sickle.py 文件源码 项目:Sickle 作者: wetw0rk 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def disassemble(self):

        completed_disassembly   = []

        try:
            with open(self.byte_file, "rb") as fd:
                binCode = fd.read()
        except:
            binCode = self.byte_file

        try:
            print("Disassembling shellcode in {:s}-{:s} architecture".format(self.arch, self.mode))
            mode = Cs(ARCH[self.arch], MODE[self.mode])

            for i in mode.disasm(binCode, 0x1000):
                completed_disassembly += ("0x%x: %s\t%s %s" % (
                    i.address,
                    binascii.hexlify(i.bytes).decode('utf-8'),
                    i.mnemonic,
                    i.op_str)
                ).expandtabs(25),

            for i in range(len(completed_disassembly)):
                print(completed_disassembly[i])

        except CsError as e:
            print("Something went wrong: {:s}".format(e))
parser.py 文件源码 项目:cemu 作者: hugsy 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def parseStringInCode(self, code, as_string=False):
        """
        This function will search for every line of assembly for quote(")
        pattern and convert it as a hexadecimal number.
        """
        parsed = []
        arch = self.emulator.parent.arch

        for line in code:
            i = line.find(b'"')
            if i==-1:
                # no string
                parsed.append(line)
                continue

            j = line[i+1:].find(b'"')
            if j==-1:
                # unfinished string
                parsed.append(line)
                continue

            if j != arch.ptrsize:
                # incorrect size
                parsed.append(line)
                continue

            origstr = line[i+1:i+j+1]
            hexstr  = binascii.hexlify(origstr)
            newline = line.replace(b'"%s"'%origstr, b'0x%s'%hexstr)
            parsed.append(newline)

        if as_string:
            return b'\n'.join(parsed)

        return parsed
base64.py 文件源码 项目:python- 作者: secondtonone1 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def b16encode(s):
    """Encode the bytes-like object s using Base16 and return a bytes object.
    """
    return binascii.hexlify(s).upper()
nm_commands.py 文件源码 项目:ironic-staging-drivers 作者: openstack 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _bytehex(data):
    """Iterate by one byte with hexlify() output."""
    for i in range(0, len(data), 2):
        yield data[i:i + 2]
nm_commands.py 文件源码 项目:ironic-staging-drivers 作者: openstack 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _hexarray(data):
    """Converting binary data to list of hex bytes as strings."""
    return ['0x' + x.decode() for x in _bytehex(binascii.hexlify(data))]
iotclient.py 文件源码 项目:IotCenter 作者: panjanek 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def handleUdpMessage(self, message, remoteAddr):
        self.logger.debug("    handling decoded UDP message from server")
        if str(message.deviceId) == str(self.deviceId):
            self.logger.debug("Validating counters in incoming server message: local={0},{1}, message={2},{3}".format(self.udpSentCounter, self.udpReceivedCounter, message.counter1, message.counter2))
            if (message.counter1 > self.udpReceivedCounter and message.counter2 >= self.udpSentCounter - 5):
                self.udpReceivedCounter = message.counter1
                self.logger.info("Counters OK. Received valid message from server at {0}:{1} with payload {2}".format(remoteAddr[0], remoteAddr[1], message.payload))
                self.saveState()
                self.passToHandler(message.payload)
            else:
                self.logger.warning("Invalid counters in incoming message. local={0},{1}, message={2},{3} - discarding".format(self.udpSentCounter, self.udpReceivedCounter, message.counter1, message.counter2))
        else:
            self.logger.warning("Device key mismatch! local=%s, incoming=%s", binascii.hexlify(self.deviceId), binascii.hexlify(message.deviceId))


问题


面经


文章

微信
公众号

扫码关注公众号