当前位置: 首页>>代码示例>>Python>>正文


Python binascii.unhexlify方法代码示例

本文整理汇总了Python中binascii.unhexlify方法的典型用法代码示例。如果您正苦于以下问题:Python binascii.unhexlify方法的具体用法?Python binascii.unhexlify怎么用?Python binascii.unhexlify使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在binascii的用法示例。


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

示例1: test_parse_packet

# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import unhexlify [as 别名]
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']) 
开发者ID:smarthall,项目名称:python-lifx-sdk,代码行数:20,代码来源:test_protocol.py

示例2: NewConnection

# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import unhexlify [as 别名]
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" 
开发者ID:D4Vinci,项目名称:ReverseHttp,代码行数:18,代码来源:Listener.py

示例3: b16decode

# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import unhexlify [as 别名]
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. 
开发者ID:war-and-code,项目名称:jawfish,代码行数:25,代码来源:base64.py

示例4: app_sign

# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import unhexlify [as 别名]
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 
开发者ID:qinyuanpei,项目名称:wechat-analyse,代码行数:21,代码来源:auth.py

示例5: assert_fingerprint

# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import unhexlify [as 别名]
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))) 
开发者ID:danielecook,项目名称:gist-alfred,代码行数:27,代码来源:ssl_.py

示例6: address

# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import unhexlify [as 别名]
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))) 
开发者ID:monero-ecosystem,项目名称:monero-python,代码行数:26,代码来源:address.py

示例7: transactions

# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import unhexlify [as 别名]
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 
开发者ID:monero-ecosystem,项目名称:monero-python,代码行数:21,代码来源:jsonrpc.py

示例8: public_address

# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import unhexlify [as 别名]
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])) 
开发者ID:monero-ecosystem,项目名称:monero-python,代码行数:26,代码来源:seed.py

示例9: get_md5_hash

# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import unhexlify [as 别名]
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 
开发者ID:mehulj94,项目名称:Radium,代码行数:26,代码来源:skype.py

示例10: exploit

# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import unhexlify [as 别名]
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() 
开发者ID:metalnas,项目名称:loubia,代码行数:22,代码来源:loubia.py

示例11: _convert_hexstring

# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import unhexlify [as 别名]
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')) 
开发者ID:eerimoq,项目名称:asn1tools,代码行数:20,代码来源:__init__.py

示例12: decode

# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import unhexlify [as 别名]
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) 
开发者ID:eerimoq,项目名称:asn1tools,代码行数:20,代码来源:xer.py

示例13: read_bits

# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import unhexlify [as 别名]
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')) 
开发者ID:eerimoq,项目名称:asn1tools,代码行数:20,代码来源:per.py

示例14: update

# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import unhexlify [as 别名]
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 
开发者ID:vijos,项目名称:vj4,代码行数:25,代码来源:token.py

示例15: _signature

# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import unhexlify [as 别名]
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 
开发者ID:hyperledger,项目名称:iroha-python,代码行数:18,代码来源:iroha.py


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