Python binascii.unhexlify() Examples

The following are 30 code examples of binascii.unhexlify(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module binascii , or try the search function .
Example #1
Source File: __init__.py    From asn1tools with MIT License 6 votes vote down vote up
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')) 
Example #2
Source File: seed.py    From monero-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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])) 
Example #3
Source File: ssl_.py    From ServerlessCrawler-VancouverRealState with MIT License 6 votes vote down vote up
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))) 
Example #4
Source File: ssl_.py    From ServerlessCrawler-VancouverRealState with MIT License 6 votes vote down vote up
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))) 
Example #5
Source File: ssl_.py    From gist-alfred with MIT License 6 votes vote down vote up
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))) 
Example #6
Source File: skype.py    From Radium with Apache License 2.0 6 votes vote down vote up
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 
Example #7
Source File: auth.py    From wechat-analyse with MIT License 6 votes vote down vote up
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 
Example #8
Source File: base64.py    From jawfish with MIT License 6 votes vote down vote up
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. 
Example #9
Source File: address.py    From monero-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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))) 
Example #10
Source File: ssl_.py    From ServerlessCrawler-VancouverRealState with MIT License 6 votes vote down vote up
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))) 
Example #11
Source File: loubia.py    From loubia with GNU General Public License v3.0 6 votes vote down vote up
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() 
Example #12
Source File: ssl_.py    From recruit with Apache License 2.0 6 votes vote down vote up
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))) 
Example #13
Source File: Listener.py    From ReverseHttp with GNU General Public License v3.0 6 votes vote down vote up
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" 
Example #14
Source File: xer.py    From asn1tools with MIT License 6 votes vote down vote up
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) 
Example #15
Source File: jsonrpc.py    From monero-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #16
Source File: token.py    From vj4 with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #17
Source File: ssl_.py    From core with MIT License 6 votes vote down vote up
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))) 
Example #18
Source File: ssl_.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
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))) 
Example #19
Source File: test_protocol.py    From python-lifx-sdk with MIT License 6 votes vote down vote up
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']) 
Example #20
Source File: iroha.py    From iroha-python with Apache License 2.0 6 votes vote down vote up
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 
Example #21
Source File: per.py    From asn1tools with MIT License 6 votes vote down vote up
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')) 
Example #22
Source File: amqp.py    From tomodachi with MIT License 5 votes vote down vote up
def decode_routing_key(cls, encoded_routing_key: str) -> str:
        def decode(match: Match) -> str:
            return binascii.unhexlify(match.group(1).encode('utf-8')).decode('utf-8')

        return re.sub(r'___([a-f0-9]{2}|[a-f0-9]{4}|[a-f0-9]{6}|[a-f0-9]{8})_', decode, encoded_routing_key) 
Example #23
Source File: utils.py    From solcrypto with GNU General Public License v3.0 5 votes vote down vote up
def packl(lnum):
    if lnum == 0:
        return b'\0'
    s = hex(lnum)[2:].rstrip('L')
    if len(s) & 1:
        s = '0' + s
    return binascii.unhexlify(s) 
Example #24
Source File: token.py    From vj4 with GNU Affero General Public License v3.0 5 votes vote down vote up
def delete(token_id: str, token_type: int):
  """Delete a token.

  Args:
    token_id: token ID.
    token_type: type of the token.

  Returns:
    True if deleted, or False.
  """
  return await delete_by_hashed_id(_get_id(binascii.unhexlify(token_id)), token_type) 
Example #25
Source File: aws_sns_sqs.py    From tomodachi with MIT License 5 votes vote down vote up
def decode_topic(cls, encoded_topic: str) -> str:
        def decode(match: Match) -> str:
            return binascii.unhexlify(match.group(1).encode('utf-8')).decode('utf-8')

        return re.sub(r'___([a-f0-9]{2}|[a-f0-9]{4}|[a-f0-9]{6}|[a-f0-9]{8})_', decode, encoded_topic) 
Example #26
Source File: plasma.py    From RATDecoders with MIT License 5 votes vote down vote up
def get_config(self):
        '''
        This is the main entry
        :return:
        '''

        config_dict = {}

        # Getting resource is tough so instead we grab the base64 string from the raw
        file_data = self.file_info.file_data
        re_pattern = b'[a-zA-Z0-9+/]{60,}={0,2}'
        conf_string = re.findall(re_pattern, file_data)[0]

        password = "IUWEEQWIOER$89^*(&@^$*&#@$HAFKJHDAKJSFHjd89379327AJHFD*&#($hajklshdf##*$&^(AAA"

        # b64decode
        conf_string = b64decode(conf_string)

        

        # Derive Key
        key_hash = hashlib.md5(password.encode('utf-8')).hexdigest()
        aes_key = key_hash[:30] + key_hash + '00'

        # Decrypt
        decrypted = crypto.decrypt_aes(binascii.unhexlify(aes_key), conf_string)

        string_list = decrypted.decode('utf-8').split('*')

        config_dict = {}
        config_dict["Domain"] = string_list[1]
        config_dict["Port"] = string_list[2]
        config_dict["Password"] = string_list[3]
        config_dict["Install Name"] = string_list[4]
        config_dict["Startup Name"] = string_list[5]
        config_dict["Campaign ID"] = string_list[6]
        config_dict["Backup Domain"] = string_list[7]


        self.config = config_dict 
Example #27
Source File: workflow.py    From Quiver-alfred with MIT License 5 votes vote down vote up
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 
Example #28
Source File: files.py    From ampy with MIT License 5 votes vote down vote up
def get(self, filename):
        """Retrieve the contents of the specified file and return its contents
        as a byte string.
        """
        # Open the file and read it a few bytes at a time and print out the
        # raw bytes.  Be careful not to overload the UART buffer so only write
        # a few bytes at a time, and don't use print since it adds newlines and
        # expects string data.
        command = """
            import sys
            import ubinascii
            with open('{0}', 'rb') as infile:
                while True:
                    result = infile.read({1})
                    if result == b'':
                        break
                    len = sys.stdout.write(ubinascii.hexlify(result))
        """.format(
            filename, BUFFER_SIZE
        )
        self._pyboard.enter_raw_repl()
        try:
            out = self._pyboard.exec_(textwrap.dedent(command))
        except PyboardError as ex:
            # Check if this is an OSError #2, i.e. file doesn't exist and
            # rethrow it as something more descriptive.
            try:
                if ex.args[2].decode("utf-8").find("OSError: [Errno 2] ENOENT") != -1:
                    raise RuntimeError("No such file: {0}".format(filename))
                else:
                    raise ex
            except UnicodeDecodeError:
                raise ex
        self._pyboard.exit_raw_repl()
        return binascii.unhexlify(out) 
Example #29
Source File: ssd_internal_keys.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def ret_wildcard_hkey():
    issuer_name_hash = unhexlify('040130')
    issuer_key_hash = unhexlify('040130')
    serial_number = unhexlify('020100')
    hkey = (issuer_name_hash, issuer_key_hash, serial_number)
    return hkey 
Example #30
Source File: oer.py    From asn1tools with MIT License 5 votes vote down vote up
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())

        self.number_of_bits -= number_of_bits
        mask = ((1 << number_of_bits) - 1)
        value = ((self.value >> self.number_of_bits) & mask)
        value &= mask
        value |= (0x80 << number_of_bits)

        return binascii.unhexlify(hex(value)[4:].rstrip('L'))