Python string.hexdigits() Examples

The following are 30 code examples of string.hexdigits(). 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 string , or try the search function .
Example #1
Source File: c_preproc.py    From 802.11ah-ns3 with GNU General Public License v2.0 6 votes vote down vote up
def parse_char(txt):
	if not txt:raise PreprocError("attempted to parse a null char")
	if txt[0]!='\\':
		return ord(txt)
	c=txt[1]
	if c=='x':
		if len(txt)==4 and txt[3]in string.hexdigits:return int(txt[2:],16)
		return int(txt[2:],16)
	elif c.isdigit():
		if c=='0'and len(txt)==2:return 0
		for i in 3,2,1:
			if len(txt)>i and txt[1:1+i].isdigit():
				return(1+i,int(txt[1:1+i],8))
	else:
		try:return chr_esc[c]
		except KeyError:raise PreprocError("could not parse char literal '%s'"%txt) 
Example #2
Source File: test_caching_integration.py    From intake with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_disable_caching(catalog_cache):
    conf['cache_disabled'] = True

    cat = catalog_cache['test_cache']
    cache = cat.cache[0]

    cache_paths = cache.load(cat._urlpath, output=False)
    cache_path = cache_paths[-1]

    assert cache_path == cat._urlpath

    conf['cache_disabled'] = False

    cache_paths = cache.load(cat._urlpath, output=False)
    cache_path = cache_paths[-1]

    assert cache._cache_dir in cache_path
    assert os.path.isfile(cache_path)

    cache_id = os.path.basename(os.path.dirname(cache_path))
    # Checking for md5 hash
    assert all(c in string.hexdigits for c in cache_id)
    cache.clear_all() 
Example #3
Source File: test_caching_integration.py    From intake with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_ds_set_cache_dir(catalog_cache):
    cat = catalog_cache['test_cache']()
    defaults = cat.cache_dirs

    new_cache_dir = os.path.join(os.getcwd(), 'test_cache_dir')
    cat.set_cache_dir(new_cache_dir)

    cache = cat.cache[0]
    assert make_path_posix(cache._cache_dir) == make_path_posix(new_cache_dir)

    cache_paths = cache.load(cat._urlpath, output=False)
    cache_path = cache_paths[-1]
    expected_cache_dir = make_path_posix(new_cache_dir)

    assert expected_cache_dir in cache_path
    assert defaults[0] not in cache_path
    assert os.path.isfile(cache_path)

    cache_id = os.path.basename(os.path.dirname(cache_path))
    # Checking for md5 hash
    assert all(c in string.hexdigits for c in cache_id)
    cache.clear_all()

    shutil.rmtree(expected_cache_dir) 
Example #4
Source File: casm.py    From stream with MIT License 6 votes vote down vote up
def s_hexlit(s, t):
  if s.peek(2, True) != '0x':
    return False

  s.get()
  s.get()

  lit = ""
  while not s.empty() and s.peek() in string.hexdigits:
    lit += s.get()

  if not lit:
    return False

  t.append(int(lit, 16))
  return True 
Example #5
Source File: casm.py    From stream with MIT License 6 votes vote down vote up
def s_hexlit(s, t):
  if s.peek(2, True) != '0x':
    return False

  s.get()
  s.get()

  lit = ""
  while not s.empty() and s.peek() in string.hexdigits:
    lit += s.get()

  if not lit:
    return False

  t.append((TokenTypes.LITERAL_INT, int(lit, 16)))
  return True 
Example #6
Source File: configurator.py    From friendly-telegram with GNU Affero General Public License v3.0 6 votes vote down vote up
def api_config():
    """Request API config from user and set"""
    code, hash_value = DIALOG.inputbox("Enter your API Hash")
    if code == DIALOG.OK:
        if len(hash_value) != 32 or any(it not in string.hexdigits for it in hash_value):
            DIALOG.msgbox("Invalid hash")
            return
        string1 = "HASH = \"" + hash_value + "\""
        code, id_value = DIALOG.inputbox("Enter your API ID")
        if not id_value or any(it not in string.digits for it in id_value):
            DIALOG.msgbox("Invalid ID")
            return
        string2 = "ID = \"" + id_value + "\""
        with open(os.path.join(utils.get_base_dir(), "api_token.py"), "w") as file:
            file.write(string1 + "\n" + string2 + "\n")
        DIALOG.msgbox("API Token and ID set.") 
Example #7
Source File: docker.py    From picoCTF with MIT License 6 votes vote down vote up
def post(self, digest):
        """
        Create a running instance from the container image digest
        """
        # Containers are mapped to teams
        user_account = api.user.get_user()
        tid = user_account['tid']

        # fail fast on invalid requests
        if any(char not in string.hexdigits + "sha:" for char in digest):
            raise PicoException("Invalid image digest", 400)

        # Create the container
        result = api.docker.create(tid, digest)

        return jsonify({"success": result['success'], "message": result['message']}) 
Example #8
Source File: docker.py    From picoCTF with MIT License 6 votes vote down vote up
def delete(self, digest, container_id):
        """
        Stop a running container.
        """

        # fail fast on invalid requests
        if any(char not in string.hexdigits for char in container_id):
            raise PicoException("Invalid container ID", 400)

        # Delete the container
        result = api.docker.delete(container_id)

        if result:
            return jsonify({"success": True, "message": "Challenge stopped"})
        else:
            return jsonify({"success": False, "message": "Error stopping challenge"}) 
Example #9
Source File: APDUHexValidator.py    From pyscard with GNU Lesser General Public License v2.1 6 votes vote down vote up
def OnChar(self, event):
        key = event.GetKeyCode()

        if wx.WXK_SPACE == key or chr(key) in string.hexdigits:
            value = event.GetEventObject().GetValue() + chr(key)
            if apduregexp.match(value):
                event.Skip()
            return

        if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255:
            event.Skip()
            return

        if not wx.Validator_IsSilent():
            wx.Bell()

        return 
Example #10
Source File: chunk.py    From HTTPWookiee with GNU General Public License v3.0 6 votes vote down vote up
def step_size(self, char):
        if char in string.hexdigits:
            return self._add_size_char(char)
        if ' ' == char:
            return self.STATUS_AFTER_SIZE
        if '\t' == char:
            self.setError(self.ERROR_BAD_SPACE, critical=False)
            return self.STATUS_AFTER_SIZE
        if ';' == char:
            return self.STATUS_TRAILER
        if '\r' == char:
            self.eof += u'[CR]'
            return self.STATUS_AFTER_CR
        if '\n' == char:
            self.setError(self.ERROR_LF_WITHOUT_CR, critical=False)
            self.eof += u'[LF]'
            return self.STATUS_END
        # other chars are bad
        self.setError(self.ERROR_BAD_CHUNK_HEADER)
        return self.STATUS_END 
Example #11
Source File: chunk.py    From HTTPWookiee with GNU General Public License v3.0 6 votes vote down vote up
def step_size_start(self, char):
        if char in string.hexdigits:
            return self._add_size_char(char, start=True)
        if ' ' == char:
            return self.STATUS_AFTER_SIZE
        if '\t' == char:
            self.setError(self.ERROR_BAD_SPACE, critical=False)
            return self.STATUS_AFTER_SIZE
        if ';' == char:
            return self.STATUS_TRAILER
        if '\r' == char:
            self.eof += u'[CR]'
            return self.STATUS_AFTER_CR
        if '\n' == char:
            self.setError(self.ERROR_LF_WITHOUT_CR, critical=False)
            self.eof += u'[LF]'
            return self.STATUS_END
        # other chars are bad
        self.setError(self.ERROR_BAD_CHUNK_HEADER)
        return self.STATUS_END 
Example #12
Source File: sniffer.py    From ddt4all with GNU General Public License v3.0 6 votes vote down vote up
def callback(self, stream):
        data = str(stream).replace(" ", "").strip()

        if '0:' in data:
            return

        if len(data) > 16:
            print "Frame length error : ", data
            return

        if not all(c in string.hexdigits for c in data):
            print _("Frame hex error : "), data
            return

        data = data.replace(' ', '').ljust(16, "0")

        if self.currentrequest:
            values = self.currentrequest.get_values_from_stream(data)
            i = 0
            for name in self.names:
                if name in values:
                    value = values[name]
                    if value is not None:
                        self.table.item(i, 0).setText(value)
                i += 1 
Example #13
Source File: utils.py    From indy-plenum with Apache License 2.0 6 votes vote down vote up
def isHex(val: str) -> bool:
    """
    Return whether the given str represents a hex value or not

    :param val: the string to check
    :return: whether the given str represents a hex value
    """
    if isinstance(val, bytes):
        # only decodes utf-8 string
        try:
            val = val.decode()
        except ValueError:
            return False
    return isinstance(val, str) and all(c in string.hexdigits for c in val)

# decorator 
Example #14
Source File: dnsrecon.py    From Yuki-Chan-The-Auto-Pentest with MIT License 6 votes vote down vote up
def check_wildcard(res, domain_trg):
    """
    Function for checking if Wildcard resolution is configured for a Domain
    """
    wildcard = None
    test_name = ''.join(Random().sample(string.hexdigits + string.digits,
                                        12)) + '.' + domain_trg
    ips = res.get_a(test_name)

    if len(ips) > 0:
        print_debug('Wildcard resolution is enabled on this domain')
        print_debug('It is resolving to {0}'.format(''.join(ips[0][2])))
        print_debug("All queries will resolve to this address!!")
        wildcard = ''.join(ips[0][2])

    return wildcard 
Example #15
Source File: mod_shellshock.py    From ITWSV with MIT License 6 votes vote down vote up
def __init__(self, crawler, persister, logger, attack_options):
        Attack.__init__(self, crawler, persister, logger, attack_options)
        empty_func = "() { :;}; "

        self.rand_string = "".join([random.choice(string.hexdigits) for _ in range(32)])
        hex_string = hexlify(self.rand_string.encode())
        bash_string = ""
        for i in range(0, 64, 2):
            bash_string += "\\x" + hex_string[i:i+2].decode()

        cmd = "echo; echo; echo -e '{0}';".format(bash_string)

        self.hdrs = {
            "user-agent": empty_func + cmd,
            "referer": empty_func + cmd,
            "cookie": empty_func + cmd
        } 
Example #16
Source File: jsunfuck.py    From script.module.urlresolver with GNU General Public License v2.0 5 votes vote down vote up
def __handle_unescape(self, key):
        start = 0
        while True:
            start_js = self.js
            offset = self.js.find(key, start)
            if offset == -1:
                break

            offset += len(key)
            expr = ''
            extra = ''
            last_c = self.js[offset - 1]
            abort = False
            for i, c in enumerate(self.js[offset:]):
                extra += c
                if c == ')':
                    break
                elif (i > 0 and c == '(') or (c == '[' and last_c != '+'):
                    abort = True
                    break
                elif c == '%' or c in string.hexdigits:
                    expr += c
                last_c = c

            if not abort:
                self.js = self.js.replace(key + extra, urllib_parse.unquote(expr))

                if start_js == self.js:
                    break
            else:
                start = offset 
Example #17
Source File: embedwiz.py    From calebj-cogs with GNU General Public License v3.0 5 votes vote down vote up
def color_converter(color):
    if type(color) is int:
        if color < 0 or color > 0xffffff:
            raise ValueError('Color value is outside of valid range')
        return '%06x' % color
    color = color.strip('#')
    if color.startswith('0x'):
        color = color[2:]
    if len(color) != 6 or set(color) - set(string.hexdigits):
        raise ValueError('Invalid color hex value')
    return color 
Example #18
Source File: controller_inject.py    From ibeis with Apache License 2.0 5 votes vote down vote up
def create_key():
    hyphen_list = [8, 13, 18, 23]
    key_list = ['-' if _ in hyphen_list else random.choice(string.hexdigits)
                for _ in xrange(36) ]
    return ''.join(key_list).upper() 
Example #19
Source File: msvs.py    From pivy with ISC License 5 votes vote down vote up
def _hexdigest(s):
    """Return a string as a string of hex characters.
    """
    # NOTE:  This routine is a method in the Python 2.0 interface
    # of the native md5 module, but we want SCons to operate all
    # the way back to at least Python 1.5.2, which doesn't have it.
    h = string.hexdigits
    r = ''
    for c in s:
        i = ord(c)
        r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
    return r 
Example #20
Source File: _scons_hashlib.py    From pivy with ISC License 5 votes vote down vote up
def hexdigest(self):
            h = string.hexdigits
            r = ''
            for c in self.digest():
                i = ord(c)
                r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
            return r 
Example #21
Source File: test_string.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_attrs(self):
        string.whitespace
        string.lowercase
        string.uppercase
        string.letters
        string.digits
        string.hexdigits
        string.octdigits
        string.punctuation
        string.printable 
Example #22
Source File: test_md5.py    From oss-ftp with MIT License 5 votes vote down vote up
def hexstr(s):
    import string
    h = string.hexdigits
    r = ''
    for c in s:
        i = ord(c)
        r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
    return r 
Example #23
Source File: rocrack-ng.py    From networking with GNU General Public License v3.0 5 votes vote down vote up
def hexing():
	for i in range(160):
		b = "\r" + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " +str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " +str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper() + " " + str(random.choice(string.hexdigits)).upper() + str(random.choice(string.hexdigits)).upper()
		sys.stdout.write(b)
		time.sleep(0.1)
		sys.stdout.flush() 
Example #24
Source File: test_hashlib.py    From oss-ftp with MIT License 5 votes vote down vote up
def hexstr(s):
    import string
    h = string.hexdigits
    r = ''
    for c in s:
        i = ord(c)
        r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
    return r 
Example #25
Source File: test_string.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_attrs(self):
        string.whitespace
        string.lowercase
        string.uppercase
        string.letters
        string.digits
        string.hexdigits
        string.octdigits
        string.punctuation
        string.printable 
Example #26
Source File: test_md5.py    From BinderFilter with MIT License 5 votes vote down vote up
def hexstr(s):
    import string
    h = string.hexdigits
    r = ''
    for c in s:
        i = ord(c)
        r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
    return r 
Example #27
Source File: initial_setup.py    From friendly-telegram with GNU Affero General Public License v3.0 5 votes vote down vote up
def set_tg_api(self, request):
        if self.client_data and await self.check_user(request) is None:
            return web.Response(status=302, headers={"Location": "/"})  # They gotta sign in.
        text = await request.text()
        if len(text) < 36:
            return web.Response(status=400)
        api_id = text[32:]
        api_hash = text[:32]
        if any(c not in string.hexdigits for c in api_hash) or any(c not in string.digits for c in api_id):
            return web.Response(status=400)
        with open(os.path.join(utils.get_base_dir(), "api_token.py"), "w") as f:
            f.write("HASH = \"" + api_hash + "\"\nID = \"" + api_id + "\"\n")
        self.api_token = collections.namedtuple("api_token", ("ID", "HASH"))(api_id, api_hash)
        self.api_set.set()
        return web.Response() 
Example #28
Source File: utils.py    From cemu with MIT License 5 votes vote down vote up
def ishex(x:string) -> bool:
    if x.startswith("0x") or x.startswith("0X"):
        x = x[2:]
    return all([c in string.hexdigits for c in x]) 
Example #29
Source File: test_hashlib.py    From BinderFilter with MIT License 5 votes vote down vote up
def hexstr(s):
    import string
    h = string.hexdigits
    r = ''
    for c in s:
        i = ord(c)
        r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
    return r 
Example #30
Source File: dn.py    From teleport with Apache License 2.0 5 votes vote down vote up
def _validate_attribute_value(attribute_value):
    if not attribute_value:
        return False

    if attribute_value[0] == '#':  # only hex characters are valid
        for c in attribute_value:
            if c not in hexdigits:  # allowed only hex digits as per RFC 4514
                raise LDAPInvalidDnError('character ' + c + ' not allowed in hex representation of attribute value')
        if len(attribute_value) % 2 == 0:  # string must be # + HEX HEX (an odd number of chars)
            raise LDAPInvalidDnError('hex representation must be in the form of <HEX><HEX> pairs')
    if attribute_value[0] == ' ':  # unescaped space cannot be used as leading or last character
        raise LDAPInvalidDnError('SPACE must be escaped as leading character of attribute value')
    if attribute_value.endswith(' ') and not attribute_value.endswith('\\ '):
        raise LDAPInvalidDnError('SPACE must be escaped as trailing character of attribute value')

    state = STATE_ANY
    for c in attribute_value:
        if state == STATE_ANY:
            if c == '\\':
                state = STATE_ESCAPE
            elif c in '"#+,;<=>\00':
                raise LDAPInvalidDnError('special character ' + c + ' must be escaped')
        elif state == STATE_ESCAPE:
            if c in hexdigits:
                state = STATE_ESCAPE_HEX
            elif c in ' "#+,;<=>\\\00':
                state = STATE_ANY
            else:
                raise LDAPInvalidDnError('invalid escaped character ' + c)
        elif state == STATE_ESCAPE_HEX:
            if c in hexdigits:
                state = STATE_ANY
            else:
                raise LDAPInvalidDnError('invalid escaped character ' + c)

    # final state
    if state != STATE_ANY:
        raise LDAPInvalidDnError('invalid final character')

    return True