Python源码示例:binascii.unhexlify()

示例1
def test_parse_packet(self):
        for kwargs, args, packet, vals in EXAMPLE_PACKETS:
            parsed = lifx.protocol.parse_packet(unhexlify(packet))

            size = len(unhexlify(packet))

            # Check data we sent
            self.assertEqual(parsed.frame_header.size, size)
            self.assertEqual(parsed.frame_header.protocol, 1024)
            self.assertEqual(parsed.frame_header.source, kwargs['source'])
            self.assertEqual(parsed.frame_address.target, kwargs['target'])
            self.assertEqual(parsed.frame_address.ack_required, kwargs['ack_required'])
            self.assertEqual(parsed.frame_address.res_required, kwargs['res_required'])
            self.assertEqual(parsed.frame_address.sequence, kwargs['sequence'])
            self.assertEqual(parsed.protocol_header.pkt_type, kwargs['pkt_type'])

            # Check other data
            self.assertEqual(parsed.frame_header.tagged, vals['tagged']) 
示例2
def NewConnection(self, ip):
        ip = binascii.unhexlify(ip)
        try:
            if ip not in added:
                a = open("Connections.txt","a")
                added.append(ip)
                a.write(str(ip)+"\n")
                a.close()
                return "Ok"
        except:
            if ip not in added:
                a = open("Connections.txt","w")
                added.append(ip)
                a.write(str(ip)+"\n")
                a.close()
                return "Ok" 
示例3
def b16decode(s, casefold=False):
    """Decode a Base16 encoded byte string.

    s is the byte string to decode.  Optional casefold is a flag
    specifying whether a lowercase alphabet is acceptable as input.
    For security purposes, the default is False.

    The decoded byte string is returned.  binascii.Error is raised if
    s were incorrectly padded or if there are non-alphabet characters
    present in the string.
    """
    s = _bytes_from_decode_data(s)
    if casefold:
        s = s.upper()
    if re.search(b'[^0-9A-F]', s):
        raise binascii.Error('Non-base16 digit found')
    return binascii.unhexlify(s)



# Legacy interface.  This code could be cleaned up since I don't believe
# binascii has any line length limitations.  It just doesn't seem worth it
# though.  The files should be opened in binary mode. 
示例4
def app_sign(self, expired=0):
        if not self._secret_id or not self._secret_key:
            return self.AUTH_SECRET_ID_KEY_ERROR

        puserid = ''
        if self._userid != '':
            if len(self._userid) > 64:
                return self.AUTH_URL_FORMAT_ERROR
            puserid = self._userid
 
        now = int(time.time())
        rdm = random.randint(0, 999999999)
        plain_text = 'a=' + self._appid + '&k=' + self._secret_id + '&e=' + str(expired) + '&t=' + str(now) + '&r=' + str(rdm) + '&u=' + puserid + '&f=' 
        bin = hmac.new(self._secret_key.encode(), plain_text.encode(), hashlib.sha1)
        s = bin.hexdigest()
        s = binascii.unhexlify(s)
        s = s + plain_text.encode('ascii')
        signature = base64.b64encode(s).rstrip()    #生成签名
        return signature 
示例5
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))) 
示例6
def address(addr, label=None):
    """Discover the proper class and return instance for a given Monero address.

    :param addr: the address as a string-like object
    :param label: a label for the address (defaults to `None`)

    :rtype: :class:`Address`, :class:`SubAddress` or :class:`IntegratedAddress`
    """
    addr = addr.decode() if isinstance(addr, bytes) else str(addr)
    if _ADDR_REGEX.match(addr):
        netbyte = bytearray(unhexlify(base58.decode(addr)))[0]
        if netbyte in Address._valid_netbytes:
            return Address(addr, label=label)
        elif netbyte in SubAddress._valid_netbytes:
            return SubAddress(addr, label=label)
        raise ValueError("Invalid address netbyte {nb:x}. Allowed values are: {allowed}".format(
            nb=netbyte,
            allowed=", ".join(map(
                lambda b: '%02x' % b,
                sorted(Address._valid_netbytes + SubAddress._valid_netbytes)))))
    elif _IADDR_REGEX.match(addr):
        return IntegratedAddress(addr)
    raise ValueError("Address must be either 95 or 106 characters long base58-encoded string, "
        "is {addr} ({len} chars length)".format(addr=addr, len=len(addr))) 
示例7
def transactions(self, hashes):
        res = self.raw_request('/get_transactions', {
                'txs_hashes': hashes,
                'decode_as_json': True})
        if res['status'] != 'OK':
            raise exceptions.BackendException(res['status'])
        txs = []
        for tx in res.get('txs', []):
            as_json = json.loads(tx['as_json'])
            fee = as_json.get('rct_signatures', {}).get('txnFee')
            txs.append(Transaction(
                hash=tx['tx_hash'],
                fee=from_atomic(fee) if fee else None,
                height=None if tx['in_pool'] else tx['block_height'],
                timestamp=datetime.fromtimestamp(
                    tx['block_timestamp']) if 'block_timestamp' in tx else None,
                blob=binascii.unhexlify(tx['as_hex']),
                json=as_json))
        return txs 
示例8
def public_address(self, net=const.NET_MAIN):
        """Returns the master :class:`Address <monero.address.Address>` represented by the seed.

        :param net: the network, one of `const.NET_*`; default is `const.NET_MAIN`

        :rtype: :class:`Address <monero.address.Address>`
        """
        # backward compatibility
        _net = net[:-3] if net.endswith('net') else net
        if _net != net:
            warnings.warn(
                "Argument '{:s}' is deprecated and will not be accepted in 0.8, "
                "use one of monero.const.NET_*".format(net),
                DeprecationWarning)
            net = _net
        if net not in const.NETS:
            raise ValueError(
                "Invalid net argument '{:s}'. Must be one of monero.const.NET_*".format(net))
        netbyte = (18, 53, 24)[const.NETS.index(net)]
        data = "{:x}{:s}{:s}".format(netbyte, self.public_spend_key(), self.public_view_key())
        h = keccak_256()
        h.update(unhexlify(data))
        checksum = h.hexdigest()
        return address(base58.encode(data + checksum[0:8])) 
示例9
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 
示例10
def exploit():
	global verbose, packet, webshell
	t3_handshake()
	update_payload()
	update_length()
	if webshell: 
		print '[INFO] Deploying webshell\n'
	#if verbose: 
		#print '[INFO] Sending packet:\n'+packet+'\n'
	try:
		sock.send(binascii.unhexlify(packet))
	except Exception as e:
		if e.args[1] == 'Broken pipe':
			print '[ERROR] Broken pipe error. Is backend ssl enabled ?\n'
			exit()
		elif e.args[1] == 'No route to host' :
			print '[ERROR] No route to host. Do you know what you\'re doing ?'
			exit()
	print '[INFO] Malicious packet sent\n'
	sock.close() 
示例11
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')) 
示例12
def decode(self, element):
        encoded = element.text

        if encoded is None:
            number_of_bits = 0
            decoded = b''
        else:
            number_of_bits = len(encoded)
            decoded = int(encoded, 2)
            decoded |= (0x80 << number_of_bits)
            rest = (number_of_bits % 8)

            if rest != 0:
                decoded <<= (8 - rest)

            decoded = binascii.unhexlify(hex(decoded).rstrip('L')[4:])

        return (decoded, number_of_bits) 
示例13
def read_bits(self, number_of_bits):
        """Read given number of bits.

        """

        if number_of_bits > self.number_of_bits:
            raise OutOfDataError(self.number_of_read_bits())

        offset = self.number_of_read_bits()
        value = self.value[offset:offset + number_of_bits]
        self.number_of_bits -= number_of_bits
        value = '10000000' + value
        number_of_alignment_bits = (8 - (number_of_bits % 8))

        if number_of_alignment_bits != 8:
            value += '0' * number_of_alignment_bits

        return binascii.unhexlify(hex(int(value, 2))[4:].rstrip('L')) 
示例14
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))) 
示例15
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))) 
示例16
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))) 
示例17
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))) 
示例18
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))) 
示例19
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))) 
示例20
def update(token_id: str, token_type: int, expire_seconds: int, **kwargs):
  """Update a token.

  Args:
    token_id: token ID.
    token_type: type of the token.
    expire_seconds: expire time, in seconds.
    **kwargs: extra data.

  Returns:
    The token document, or None.
  """
  id_binary = binascii.unhexlify(token_id)
  coll = db.coll('token')
  assert 'token_type' not in kwargs
  now = datetime.datetime.utcnow()
  doc = await coll.find_one_and_update(
    filter={'_id': _get_id(id_binary), 'token_type': token_type},
    update={'$set': {**kwargs,
                     'update_at': now,
                     'expire_at': now + datetime.timedelta(seconds=expire_seconds)}},
    return_document=ReturnDocument.AFTER)
  return doc 
示例21
def _signature(message, private_key):
        """
        Calculate signature for given message and private key
        :param message: proto that has payload message inside
        :param private_key: hex string with private key
        :return: a proto Signature message
        """
        public_key = IrohaCrypto.derive_public_key(private_key)
        sk = binascii.unhexlify(private_key)
        pk = binascii.unhexlify(public_key)
        message_hash = IrohaCrypto.hash(message)
        signature_bytes = ed25519.signature_unsafe(message_hash, sk, pk)
        signature = primitive_pb2.Signature()
        signature.public_key = public_key
        signature.signature = binascii.hexlify(signature_bytes)
        return signature 
示例22
def get_password(self, account, service=None):
        """Retrieve the password saved at ``service/account``.

        Raise :class:`PasswordNotFound` exception if password doesn't exist.

        :param account: name of the account the password is for, e.g.
            "Pinboard"
        :type account: ``unicode``
        :param service: Name of the service. By default, this is the workflow's
                        bundle ID
        :type service: ``unicode``
        :returns: account password
        :rtype: ``unicode``

        """
        if not service:
            service = self.bundleid

        output = self._call_security('find-generic-password', service,
                                     account, '-g')

        # Parsing of `security` output is adapted from python-keyring
        # by Jason R. Coombs
        # https://pypi.python.org/pypi/keyring
        m = re.search(
            r'password:\s*(?:0x(?P<hex>[0-9A-F]+)\s*)?(?:"(?P<pw>.*)")?',
            output)

        if m:
            groups = m.groupdict()
            h = groups.get('hex')
            password = groups.get('pw')
            if h:
                password = unicode(binascii.unhexlify(h), 'utf-8')

        self.logger.debug('got password : %s:%s', service, account)

        return password 
示例23
def craft_arp_packet(packet, dst_mac):
    arp_packet = [
        packet["htype"],
        packet["ptype"],
        packet["hlen"],
        packet["plen"],
        struct.pack("!h", 2),
        binascii.unhexlify(dst_mac.replace(':', '')),
        socket.inet_aton(packet["dst_ip"]),
        binascii.unhexlify(packet["src_mac"].replace(':', '')),
        socket.inet_aton(packet["src_ip"])]

    return arp_packet 
示例24
def craft_eth_frame(frame, dst_mac, data):
    eth_frame = [
        binascii.unhexlify(frame["src_mac"].replace(':', '')),
        binascii.unhexlify(dst_mac.replace(':', '')),
        frame["type"],
        ''.join(data)]

    return eth_frame 
示例25
def craft_garp_response(SPA, TPA, SHA, THA, eth_src, eth_dst):
    "Craft Gratuitous ARP Response Message"
    """
    Format ARP reply:
    eth_src = VMAC, eth_dst = requester_mac, SHA = VMAC, SPA = vnhip, THA = requester_mac, TPA = requester_ip

    Format gratuitous ARP:
    eth_src = VMAC, eth_dst = 00..00<part_id>, SHA = VMAC, SPA = vnhip, THA = VMAC, TPA = vnhip
    """
    arp_packet = [
        # HTYPE
        struct.pack("!h", 1),
        # PTYPE (IPv4)
        struct.pack("!h", 0x0800),
        # HLEN
        struct.pack("!B", 6),
        # PLEN
        struct.pack("!B", 4),
        # OPER (reply)
        struct.pack("!h", 2),
        # SHA
        binascii.unhexlify(SHA.replace(':', '')),
        # SPA
        socket.inet_aton(str(SPA)),
        # THA
        binascii.unhexlify(THA.replace(':', '')),
        # TPA
        socket.inet_aton(str(TPA))
    ]
    eth_frame = [
        # Destination address:
        binascii.unhexlify(eth_dst.replace(':', '')),
        # Source address:
        binascii.unhexlify(eth_src.replace(':', '')),
        # Protocol
        struct.pack("!h", ETH_TYPE_ARP),
        # Data
        ''.join(arp_packet)
    ]
    return ''.join(eth_frame) 
示例26
def test_unpack_section(self):
        for pack_type, args, packet in PACK_TEST_CASES:
            self.assertEqual(lifx.protocol.unpack_section(pack_type, unhexlify(packet)), args) 
示例27
def test_parse_packet_with_incorrect_size(self):
        packet = '240000142d000000d073d5017c0400000000000000000161000000000000000014'
        self.assertIsNone(lifx.protocol.parse_packet(unhexlify(packet))) 
示例28
def test_parse_packet_with_unknown_type(self):
        packet = '2600005442524b52d073d501cf2c00004c49465856320000842e3128d92cf7136f000000890c'
        parsed = lifx.protocol.parse_packet(unhexlify(packet))
        self.assertEqual(parsed.protocol_header.pkt_type, 111)
        self.assertEqual(parsed.payload, '\x89\x0c') 
示例29
def set_ipaddress(self, address):
        # set's the IP address from a human readable format, for IPv6, this
        # needs to be the full IPv6 address
        if self['type'].get_value() == IpAddrType.MOVE_DST_IPADDR_V4:
            self['ip_address'].set_value(socket.inet_aton(address))
        else:
            addr = address.replace(":", "")
            if len(addr) != 32:
                raise ValueError("When setting an IPv6 address, it must be in "
                                 "the full form without concatenation")
            self['ip_address'].set_value(binascii.unhexlify(addr)) 
示例30
def set_ipaddress(self, address):
        # set's the ipv6_address field from the address passed in, note this
        # needs to be the full ipv6 address,
        # e.g. fe80:0000:0000:0000:0000:0000:0000:0000 and not any short form
        address = address.replace(":", "")
        if len(address) != 32:
            raise ValueError("When setting an IPv6 address, it must be in the "
                             "full form without concatenation")
        self['ipv6_address'].set_value(binascii.unhexlify(address))