Python base64.b16encode() Examples

The following are 30 code examples for showing how to use base64.b16encode(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module base64 , or try the search function .

Example 1
Project: king-phisher   Author: rsmusllp   File: templates.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _filter_encode(self, data, encoding):
		if its.py_v3 and isinstance(data, str):
			data = data.encode('utf-8')
		encoding = encoding.lower()
		encoding = re.sub(r'^(base|rot)-(\d\d)$', r'\1\2', encoding)

		if encoding == 'base16' or encoding == 'hex':
			data = base64.b16encode(data)
		elif encoding == 'base32':
			data = base64.b32encode(data)
		elif encoding == 'base64':
			data = base64.b64encode(data)
		elif encoding == 'rot13':
			data = codecs.getencoder('rot-13')(data.decode('utf-8'))[0]
		else:
			raise ValueError('Unknown encoding type: ' + encoding)
		if its.py_v3 and isinstance(data, bytes):
			data = data.decode('utf-8')
		return data 
Example 2
Project: torf   Author: rndusr   File: _magnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def torrent(self):
        """:class:`Torrent` instance"""
        # Prevent circular import issues
        from ._torrent import Torrent
        torrent = Torrent()
        torrent.name = self.dn
        if self.tr:
            torrent.trackers = self.tr
        if self.ws:
            torrent.webseeds = self.ws
        if self.xl:
            torrent._metainfo['info']['length'] = self.xl
        if hasattr(self, '_info'):
            torrent.metainfo['info'] = self._info
        elif len(self.infohash) == 40:
            torrent._infohash = self.infohash
        else:
            # Convert base 32 to base 16 (SHA1)
            torrent._infohash = base64.b16encode(
                base64.b32decode(self.infohash)).decode('utf-8').lower()
        return torrent 
Example 3
Project: vrequest   Author: cilame   File: pyzlibaes.py    License: MIT License 6 votes vote down vote up
def crypter(ack='',iv='2769514380123456',base='b64'):
    ahk = hmac.new(b'vilame',ack.encode(),'md5').hexdigest()
    c = CrypterAES(ahk, iv)
    if base == 'b16': _encode,_decode = base64.b16encode,base64.b16decode
    if base == 'b32': _encode,_decode = base64.b32encode,base64.b32decode
    if base == 'b64': _encode,_decode = base64.b64encode,base64.b64decode
    if base == 'b85': _encode,_decode = base64.b85encode,base64.b85decode
    if base == 'urlsafe_b64': _encode,_decode = base64.urlsafe_b64encode,base64.urlsafe_b64decode
    def zbase_enc(data):
        return _encode(zlib.compress(data.encode())[2:-4]).decode()
    def zbase_dec(basedata):
        return zlib.decompress(_decode(basedata),-15).decode()
    def zencrypt(data): return c.encrypt_base(zlib.compress(data.encode())[2:-4],_encode)
    def zdecrypt(data): return zlib.decompress(c.decrypt_base(data,_decode),-15).decode()
    c.zencrypt = zencrypt
    c.zdecrypt = zdecrypt
    c.zbase_enc = zbase_enc
    c.zbase_dec = zbase_dec
    c.encrypt = lambda data:c.encrypt_base(data,_encode)
    c.decrypt = lambda data:c.decrypt_base(data,_decode).decode()
    return c 
Example 4
Project: outis   Author: SySS-Research   File: encoding.py    License: MIT License 6 votes vote down vote up
def dnshostencode(data, zone):
    """
    encodes the data in a DNS transmittable hostname, 0-9A-F
    :param data: DNS transmittable hostname data
    :param zone: DNS zone to add at the end
    :return: encoded form
    """

    # TODO: sending 0-9A-Z would be better

    res = b""
    sdata = base64.b16encode(data)

    # every 60 characters, we will add a dot
    for i in range(len(sdata)):
        res += sdata[i:i+1]
        if (i+1) % 60 == 0 and (i+1) < len(sdata):
            res += b'.'

    return res + b'.' + zone.encode('utf-8') + b'.' 
Example 5
Project: outis   Author: SySS-Research   File: encoding.py    License: MIT License 6 votes vote down vote up
def dnsip6encode(data):
    """
    encodes the data as a single IPv6 address
    :param data: data to encode
    :return: encoded form
    """

    if len(data) != 16:
        print_error("dnsip6encode: data is more or less than 16 bytes, cannot encode")
        return None

    res = b''
    reslen = 0
    for i in range(len(data)):
        res += base64.b16encode(data[i:i+1])
        reslen += 1
        if reslen % 2 == 0:
            res += b':'

    return res[:-1] 
Example 6
Project: programming-challenges   Author: anomen-s   File: tools.py    License: GNU General Public License v2.0 6 votes vote down vote up
def toHex(data, maxLen=0, upperCase=True, blockSize=0):
  if (type(data) == str):
    data = bytes(data,'utf-8')

  if maxLen:
    data = data[:maxLen]

  if blockSize:
   dataBlocks = split(data, blockSize, False)
  else:
   dataBlocks = [data]
   
  hex=' '.join([str(base64.b16encode(b),'utf-8') for b in dataBlocks])
  if not upperCase:
    hex= hex.lower()
  return hex 
Example 7
Project: XFLTReaT   Author: earthquake   File: encoding.py    License: MIT License 5 votes vote down vote up
def encode(self, text):
		return base64.b16encode(text).lower() 
Example 8
Project: python-esppy   Author: sassoftware   File: tools.py    License: Apache License 2.0 5 votes vote down vote up
def convertColormapToPalette(name):
    cmap = matplotlib.cm.get_cmap(name)
    norm = matplotlib.colors.Normalize(vmin = 0,vmax = 255)
    rgb = []
 
    for i in range(0, 255):
        k = matplotlib.colors.colorConverter.to_rgb(cmap(norm(i)))
        rgb.append(k)

    entries = 255

    h = 1.0 / (entries - 1)
    colorscale = []

    prev = None

    for k in range(entries):
        c = list(map(np.uint8,np.array(cmap(k * h)[:3]) * 255))
        value = (c[0],c[1],c[2])
        if value == prev:
            continue
        prev = value
        s = "#" + b16encode(bytes(value)).decode()
        colorscale.append(s)

    return(colorscale) 
Example 9
Project: gist-alfred   Author: danielecook   File: low_level.py    License: MIT License 5 votes vote down vote up
def _temporary_keychain():
    """
    This function creates a temporary Mac keychain that we can use to work with
    credentials. This keychain uses a one-time password and a temporary file to
    store the data. We expect to have one keychain per socket. The returned
    SecKeychainRef must be freed by the caller, including calling
    SecKeychainDelete.

    Returns a tuple of the SecKeychainRef and the path to the temporary
    directory that contains it.
    """
    # Unfortunately, SecKeychainCreate requires a path to a keychain. This
    # means we cannot use mkstemp to use a generic temporary file. Instead,
    # we're going to create a temporary directory and a filename to use there.
    # This filename will be 8 random bytes expanded into base64. We also need
    # some random bytes to password-protect the keychain we're creating, so we
    # ask for 40 random bytes.
    random_bytes = os.urandom(40)
    filename = base64.b16encode(random_bytes[:8]).decode('utf-8')
    password = base64.b16encode(random_bytes[8:])  # Must be valid UTF-8
    tempdirectory = tempfile.mkdtemp()

    keychain_path = os.path.join(tempdirectory, filename).encode('utf-8')

    # We now want to create the keychain itself.
    keychain = Security.SecKeychainRef()
    status = Security.SecKeychainCreate(
        keychain_path,
        len(password),
        password,
        False,
        None,
        ctypes.byref(keychain)
    )
    _assert_no_error(status)

    # Having created the keychain, we want to pass it off to the caller.
    return keychain, tempdirectory 
Example 10
Project: misp42splunk   Author: remg427   File: low_level.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def _temporary_keychain():
    """
    This function creates a temporary Mac keychain that we can use to work with
    credentials. This keychain uses a one-time password and a temporary file to
    store the data. We expect to have one keychain per socket. The returned
    SecKeychainRef must be freed by the caller, including calling
    SecKeychainDelete.

    Returns a tuple of the SecKeychainRef and the path to the temporary
    directory that contains it.
    """
    # Unfortunately, SecKeychainCreate requires a path to a keychain. This
    # means we cannot use mkstemp to use a generic temporary file. Instead,
    # we're going to create a temporary directory and a filename to use there.
    # This filename will be 8 random bytes expanded into base64. We also need
    # some random bytes to password-protect the keychain we're creating, so we
    # ask for 40 random bytes.
    random_bytes = os.urandom(40)
    filename = base64.b16encode(random_bytes[:8]).decode("utf-8")
    password = base64.b16encode(random_bytes[8:])  # Must be valid UTF-8
    tempdirectory = tempfile.mkdtemp()

    keychain_path = os.path.join(tempdirectory, filename).encode("utf-8")

    # We now want to create the keychain itself.
    keychain = Security.SecKeychainRef()
    status = Security.SecKeychainCreate(
        keychain_path, len(password), password, False, None, ctypes.byref(keychain)
    )
    _assert_no_error(status)

    # Having created the keychain, we want to pass it off to the caller.
    return keychain, tempdirectory 
Example 11
Project: misp42splunk   Author: remg427   File: low_level.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def _temporary_keychain():
    """
    This function creates a temporary Mac keychain that we can use to work with
    credentials. This keychain uses a one-time password and a temporary file to
    store the data. We expect to have one keychain per socket. The returned
    SecKeychainRef must be freed by the caller, including calling
    SecKeychainDelete.

    Returns a tuple of the SecKeychainRef and the path to the temporary
    directory that contains it.
    """
    # Unfortunately, SecKeychainCreate requires a path to a keychain. This
    # means we cannot use mkstemp to use a generic temporary file. Instead,
    # we're going to create a temporary directory and a filename to use there.
    # This filename will be 8 random bytes expanded into base64. We also need
    # some random bytes to password-protect the keychain we're creating, so we
    # ask for 40 random bytes.
    random_bytes = os.urandom(40)
    filename = base64.b16encode(random_bytes[:8]).decode("utf-8")
    password = base64.b16encode(random_bytes[8:])  # Must be valid UTF-8
    tempdirectory = tempfile.mkdtemp()

    keychain_path = os.path.join(tempdirectory, filename).encode("utf-8")

    # We now want to create the keychain itself.
    keychain = Security.SecKeychainRef()
    status = Security.SecKeychainCreate(
        keychain_path, len(password), password, False, None, ctypes.byref(keychain)
    )
    _assert_no_error(status)

    # Having created the keychain, we want to pass it off to the caller.
    return keychain, tempdirectory 
Example 12
Project: snowflake-connector-python   Author: snowflakedb   File: sfbinaryformat.py    License: Apache License 2.0 5 votes vote down vote up
def binary_to_snowflake(binary_value):
    """Encodes a "bytes" object for passing to Snowflake."""
    result = b16encode(binary_value)

    if isinstance(binary_value, bytearray):
        return bytearray(result)
    return result 
Example 13
Project: snowflake-connector-python   Author: snowflakedb   File: sfbinaryformat.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, name):
        name = name.upper()
        if name == 'HEX':
            self._encode = b16encode
        elif name == 'BASE64':
            self._encode = standard_b64encode
        else:
            raise InternalError(
                'Unrecognized binary format {}'.format(name)) 
Example 14
Project: picoCTF   Author: picoCTF   File: ecb.py    License: MIT License 5 votes vote down vote up
def encrypt():
    cipher = AES.new(base64.b16decode(key, casefold=True), AES.MODE_ECB)
    return base64.b16encode(cipher.encrypt(flag))


# flush output immediately 
Example 15
Project: ironpython2   Author: IronLanguages   File: test_base64.py    License: Apache License 2.0 5 votes vote down vote up
def test_b16encode(self):
        eq = self.assertEqual
        eq(base64.b16encode('\x01\x02\xab\xcd\xef'), '0102ABCDEF')
        eq(base64.b16encode('\x00'), '00')
        # Non-bytes
        eq(base64.b16encode(bytearray('\x01\x02\xab\xcd\xef')), '0102ABCDEF') 
Example 16
def _base16_encode(self, encode_string):
        encoder = base64.b16encode(encode_string)
        return encoder 
Example 17
Project: vnpy_crypto   Author: birforce   File: low_level.py    License: MIT License 5 votes vote down vote up
def _temporary_keychain():
    """
    This function creates a temporary Mac keychain that we can use to work with
    credentials. This keychain uses a one-time password and a temporary file to
    store the data. We expect to have one keychain per socket. The returned
    SecKeychainRef must be freed by the caller, including calling
    SecKeychainDelete.

    Returns a tuple of the SecKeychainRef and the path to the temporary
    directory that contains it.
    """
    # Unfortunately, SecKeychainCreate requires a path to a keychain. This
    # means we cannot use mkstemp to use a generic temporary file. Instead,
    # we're going to create a temporary directory and a filename to use there.
    # This filename will be 8 random bytes expanded into base64. We also need
    # some random bytes to password-protect the keychain we're creating, so we
    # ask for 40 random bytes.
    random_bytes = os.urandom(40)
    filename = base64.b16encode(random_bytes[:8]).decode('utf-8')
    password = base64.b16encode(random_bytes[8:])  # Must be valid UTF-8
    tempdirectory = tempfile.mkdtemp()

    keychain_path = os.path.join(tempdirectory, filename).encode('utf-8')

    # We now want to create the keychain itself.
    keychain = Security.SecKeychainRef()
    status = Security.SecKeychainCreate(
        keychain_path,
        len(password),
        password,
        False,
        None,
        ctypes.byref(keychain)
    )
    _assert_no_error(status)

    # Having created the keychain, we want to pass it off to the caller.
    return keychain, tempdirectory 
Example 18
Project: django-more   Author: ashleywaite   File: hashing.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def b16from256(val):
    """ ASCII encoded base 16 string from a raw (base 256) digest """
    return str(b16encode(bytes(val)), encoding="ascii") 
Example 19
Project: BinderFilter   Author: dxwu   File: test_base64.py    License: MIT License 5 votes vote down vote up
def test_b16encode(self):
        eq = self.assertEqual
        eq(base64.b16encode('\x01\x02\xab\xcd\xef'), '0102ABCDEF')
        eq(base64.b16encode('\x00'), '00')
        # Non-bytes
        eq(base64.b16encode(bytearray('\x01\x02\xab\xcd\xef')), '0102ABCDEF') 
Example 20
Project: python_dhcp_server   Author: niccokunzmann   File: listener.py    License: MIT License 5 votes vote down vote up
def macunpack(data):
    s = base64.b16encode(data)
    return ':'.join([s[i:i+2].decode('ascii') for i in range(0, 12, 2)]) 
Example 21
Project: oss-ftp   Author: aliyun   File: test_base64.py    License: MIT License 5 votes vote down vote up
def test_b16encode(self):
        eq = self.assertEqual
        eq(base64.b16encode('\x01\x02\xab\xcd\xef'), '0102ABCDEF')
        eq(base64.b16encode('\x00'), '00')
        # Non-bytes
        eq(base64.b16encode(bytearray('\x01\x02\xab\xcd\xef')), '0102ABCDEF') 
Example 22
Project: chinese-support-redux   Author: luoliyan   File: low_level.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _temporary_keychain():
    """
    This function creates a temporary Mac keychain that we can use to work with
    credentials. This keychain uses a one-time password and a temporary file to
    store the data. We expect to have one keychain per socket. The returned
    SecKeychainRef must be freed by the caller, including calling
    SecKeychainDelete.

    Returns a tuple of the SecKeychainRef and the path to the temporary
    directory that contains it.
    """
    # Unfortunately, SecKeychainCreate requires a path to a keychain. This
    # means we cannot use mkstemp to use a generic temporary file. Instead,
    # we're going to create a temporary directory and a filename to use there.
    # This filename will be 8 random bytes expanded into base64. We also need
    # some random bytes to password-protect the keychain we're creating, so we
    # ask for 40 random bytes.
    random_bytes = os.urandom(40)
    filename = base64.b16encode(random_bytes[:8]).decode("utf-8")
    password = base64.b16encode(random_bytes[8:])  # Must be valid UTF-8
    tempdirectory = tempfile.mkdtemp()

    keychain_path = os.path.join(tempdirectory, filename).encode("utf-8")

    # We now want to create the keychain itself.
    keychain = Security.SecKeychainRef()
    status = Security.SecKeychainCreate(
        keychain_path, len(password), password, False, None, ctypes.byref(keychain)
    )
    _assert_no_error(status)

    # Having created the keychain, we want to pass it off to the caller.
    return keychain, tempdirectory 
Example 23
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: low_level.py    License: MIT License 5 votes vote down vote up
def _temporary_keychain():
    """
    This function creates a temporary Mac keychain that we can use to work with
    credentials. This keychain uses a one-time password and a temporary file to
    store the data. We expect to have one keychain per socket. The returned
    SecKeychainRef must be freed by the caller, including calling
    SecKeychainDelete.

    Returns a tuple of the SecKeychainRef and the path to the temporary
    directory that contains it.
    """
    # Unfortunately, SecKeychainCreate requires a path to a keychain. This
    # means we cannot use mkstemp to use a generic temporary file. Instead,
    # we're going to create a temporary directory and a filename to use there.
    # This filename will be 8 random bytes expanded into base64. We also need
    # some random bytes to password-protect the keychain we're creating, so we
    # ask for 40 random bytes.
    random_bytes = os.urandom(40)
    filename = base64.b16encode(random_bytes[:8]).decode('utf-8')
    password = base64.b16encode(random_bytes[8:])  # Must be valid UTF-8
    tempdirectory = tempfile.mkdtemp()

    keychain_path = os.path.join(tempdirectory, filename).encode('utf-8')

    # We now want to create the keychain itself.
    keychain = Security.SecKeychainRef()
    status = Security.SecKeychainCreate(
        keychain_path,
        len(password),
        password,
        False,
        None,
        ctypes.byref(keychain)
    )
    _assert_no_error(status)

    # Having created the keychain, we want to pass it off to the caller.
    return keychain, tempdirectory 
Example 24
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: low_level.py    License: MIT License 5 votes vote down vote up
def _temporary_keychain():
    """
    This function creates a temporary Mac keychain that we can use to work with
    credentials. This keychain uses a one-time password and a temporary file to
    store the data. We expect to have one keychain per socket. The returned
    SecKeychainRef must be freed by the caller, including calling
    SecKeychainDelete.

    Returns a tuple of the SecKeychainRef and the path to the temporary
    directory that contains it.
    """
    # Unfortunately, SecKeychainCreate requires a path to a keychain. This
    # means we cannot use mkstemp to use a generic temporary file. Instead,
    # we're going to create a temporary directory and a filename to use there.
    # This filename will be 8 random bytes expanded into base64. We also need
    # some random bytes to password-protect the keychain we're creating, so we
    # ask for 40 random bytes.
    random_bytes = os.urandom(40)
    filename = base64.b16encode(random_bytes[:8]).decode('utf-8')
    password = base64.b16encode(random_bytes[8:])  # Must be valid UTF-8
    tempdirectory = tempfile.mkdtemp()

    keychain_path = os.path.join(tempdirectory, filename).encode('utf-8')

    # We now want to create the keychain itself.
    keychain = Security.SecKeychainRef()
    status = Security.SecKeychainCreate(
        keychain_path,
        len(password),
        password,
        False,
        None,
        ctypes.byref(keychain)
    )
    _assert_no_error(status)

    # Having created the keychain, we want to pass it off to the caller.
    return keychain, tempdirectory 
Example 25
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: low_level.py    License: MIT License 5 votes vote down vote up
def _temporary_keychain():
    """
    This function creates a temporary Mac keychain that we can use to work with
    credentials. This keychain uses a one-time password and a temporary file to
    store the data. We expect to have one keychain per socket. The returned
    SecKeychainRef must be freed by the caller, including calling
    SecKeychainDelete.

    Returns a tuple of the SecKeychainRef and the path to the temporary
    directory that contains it.
    """
    # Unfortunately, SecKeychainCreate requires a path to a keychain. This
    # means we cannot use mkstemp to use a generic temporary file. Instead,
    # we're going to create a temporary directory and a filename to use there.
    # This filename will be 8 random bytes expanded into base64. We also need
    # some random bytes to password-protect the keychain we're creating, so we
    # ask for 40 random bytes.
    random_bytes = os.urandom(40)
    filename = base64.b16encode(random_bytes[:8]).decode('utf-8')
    password = base64.b16encode(random_bytes[8:])  # Must be valid UTF-8
    tempdirectory = tempfile.mkdtemp()

    keychain_path = os.path.join(tempdirectory, filename).encode('utf-8')

    # We now want to create the keychain itself.
    keychain = Security.SecKeychainRef()
    status = Security.SecKeychainCreate(
        keychain_path,
        len(password),
        password,
        False,
        None,
        ctypes.byref(keychain)
    )
    _assert_no_error(status)

    # Having created the keychain, we want to pass it off to the caller.
    return keychain, tempdirectory 
Example 26
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: low_level.py    License: MIT License 5 votes vote down vote up
def _temporary_keychain():
    """
    This function creates a temporary Mac keychain that we can use to work with
    credentials. This keychain uses a one-time password and a temporary file to
    store the data. We expect to have one keychain per socket. The returned
    SecKeychainRef must be freed by the caller, including calling
    SecKeychainDelete.

    Returns a tuple of the SecKeychainRef and the path to the temporary
    directory that contains it.
    """
    # Unfortunately, SecKeychainCreate requires a path to a keychain. This
    # means we cannot use mkstemp to use a generic temporary file. Instead,
    # we're going to create a temporary directory and a filename to use there.
    # This filename will be 8 random bytes expanded into base64. We also need
    # some random bytes to password-protect the keychain we're creating, so we
    # ask for 40 random bytes.
    random_bytes = os.urandom(40)
    filename = base64.b16encode(random_bytes[:8]).decode('utf-8')
    password = base64.b16encode(random_bytes[8:])  # Must be valid UTF-8
    tempdirectory = tempfile.mkdtemp()

    keychain_path = os.path.join(tempdirectory, filename).encode('utf-8')

    # We now want to create the keychain itself.
    keychain = Security.SecKeychainRef()
    status = Security.SecKeychainCreate(
        keychain_path,
        len(password),
        password,
        False,
        None,
        ctypes.byref(keychain)
    )
    _assert_no_error(status)

    # Having created the keychain, we want to pass it off to the caller.
    return keychain, tempdirectory 
Example 27
Project: roca   Author: crocs-muni   File: detect.py    License: MIT License 5 votes vote down vote up
def process_mod_line_num(self, data, name, idx, num_type='hex', aux=None):
        """
        Processes particular number
        :param data:
        :param name:
        :param idx:
        :param num_type:
        :param aux:
        :return:
        """
        try:
            num = 0
            if num_type == 'base64':
                num = int(base64.b16encode(base64.b64decode(data)), 16)
            elif num_type == 'hex':
                num = int(strip_hex_prefix(data), 16)
            elif num_type == 'dec':
                num = int(data)
            else:
                raise ValueError('Unknown number format: %s' % num_type)

            js = collections.OrderedDict()
            js['type'] = 'mod-%s' % num_type
            js['fname'] = name
            js['idx'] = idx
            js['aux'] = aux
            js['n'] = '0x%x' % num

            if self.has_fingerprint(num):
                logger.warning('Fingerprint found in modulus %s idx %s ' % (name, idx))
                self.mark_and_add_effort(num, js)

                if self.do_print:
                    print(json.dumps(js))
            return TestResult(js)

        except Exception as e:
            logger.debug('Exception in testing modulus %s idx %s : %s data: %s' % (name, idx, e, data[:30]))
            self.trace_logger.log(e) 
Example 28
Project: Safejumper-for-Desktop   Author: proxysh   File: yacc.py    License: GNU General Public License v2.0 5 votes vote down vote up
def signature(self):
        try:
            from hashlib import md5
        except ImportError:
            from md5 import md5
        try:
            sig = md5()
            if self.start:
                sig.update(self.start.encode('latin-1'))
            if self.prec:
                sig.update(''.join([''.join(p) for p in self.prec]).encode('latin-1'))
            if self.tokens:
                sig.update(' '.join(self.tokens).encode('latin-1'))
            for f in self.pfuncs:
                if f[3]:
                    sig.update(f[3].encode('latin-1'))
        except (TypeError, ValueError):
            pass

        digest = base64.b16encode(sig.digest())
        if sys.version_info[0] >= 3:
            digest = digest.decode('latin-1')
        return digest

    # -----------------------------------------------------------------------------
    # validate_modules()
    #
    # This method checks to see if there are duplicated p_rulename() functions
    # in the parser module file.  Without this function, it is really easy for
    # users to make mistakes by cutting and pasting code fragments (and it's a real
    # bugger to try and figure out why the resulting parser doesn't work).  Therefore,
    # we just do a little regular expression pattern matching of def statements
    # to try and detect duplicates.
    # ----------------------------------------------------------------------------- 
Example 29
Project: satori   Author: leancloud   File: low_level.py    License: Apache License 2.0 5 votes vote down vote up
def _temporary_keychain():
    """
    This function creates a temporary Mac keychain that we can use to work with
    credentials. This keychain uses a one-time password and a temporary file to
    store the data. We expect to have one keychain per socket. The returned
    SecKeychainRef must be freed by the caller, including calling
    SecKeychainDelete.

    Returns a tuple of the SecKeychainRef and the path to the temporary
    directory that contains it.
    """
    # Unfortunately, SecKeychainCreate requires a path to a keychain. This
    # means we cannot use mkstemp to use a generic temporary file. Instead,
    # we're going to create a temporary directory and a filename to use there.
    # This filename will be 8 random bytes expanded into base64. We also need
    # some random bytes to password-protect the keychain we're creating, so we
    # ask for 40 random bytes.
    random_bytes = os.urandom(40)
    filename = base64.b16encode(random_bytes[:8]).decode('utf-8')
    password = base64.b16encode(random_bytes[8:])  # Must be valid UTF-8
    tempdirectory = tempfile.mkdtemp()

    keychain_path = os.path.join(tempdirectory, filename).encode('utf-8')

    # We now want to create the keychain itself.
    keychain = Security.SecKeychainRef()
    status = Security.SecKeychainCreate(
        keychain_path,
        len(password),
        password,
        False,
        None,
        ctypes.byref(keychain)
    )
    _assert_no_error(status)

    # Having created the keychain, we want to pass it off to the caller.
    return keychain, tempdirectory 
Example 30
Project: pex   Author: pantsbuild   File: low_level.py    License: Apache License 2.0 5 votes vote down vote up
def _temporary_keychain():
    """
    This function creates a temporary Mac keychain that we can use to work with
    credentials. This keychain uses a one-time password and a temporary file to
    store the data. We expect to have one keychain per socket. The returned
    SecKeychainRef must be freed by the caller, including calling
    SecKeychainDelete.

    Returns a tuple of the SecKeychainRef and the path to the temporary
    directory that contains it.
    """
    # Unfortunately, SecKeychainCreate requires a path to a keychain. This
    # means we cannot use mkstemp to use a generic temporary file. Instead,
    # we're going to create a temporary directory and a filename to use there.
    # This filename will be 8 random bytes expanded into base64. We also need
    # some random bytes to password-protect the keychain we're creating, so we
    # ask for 40 random bytes.
    random_bytes = os.urandom(40)
    filename = base64.b16encode(random_bytes[:8]).decode("utf-8")
    password = base64.b16encode(random_bytes[8:])  # Must be valid UTF-8
    tempdirectory = tempfile.mkdtemp()

    keychain_path = os.path.join(tempdirectory, filename).encode("utf-8")

    # We now want to create the keychain itself.
    keychain = Security.SecKeychainRef()
    status = Security.SecKeychainCreate(
        keychain_path, len(password), password, False, None, ctypes.byref(keychain)
    )
    _assert_no_error(status)

    # Having created the keychain, we want to pass it off to the caller.
    return keychain, tempdirectory