Python base64.b16decode() Examples

The following are 30 code examples for showing how to use base64.b16decode(). 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_decode(self, data, encoding):
		if its.py_v3 and isinstance(data, bytes):
			data = data.decode('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.b16decode(data)
		elif encoding == 'base32':
			data = base64.b32decode(data)
		elif encoding == 'base64':
			data = base64.b64decode(data)
		elif encoding == 'rot13':
			data = codecs.getdecoder('rot-13')(data)[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: TinyTor   Author: Marten4n6   File: tinytor.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, onion_router):
        """:type onion_router: OnionRouter"""
        self._onion_router = onion_router

        # To perform the handshake, the client needs to know an identity key
        # digest for the server, and an NTOR onion key (a curve25519 public
        # key) for that server. Call the NTOR onion key "B".  The client
        # generates a temporary key-pair:
        #     x,X = KEYGEN()
        self._ed25519 = Ed25519()
        self._x = self._ed25519.create_secret_key()
        self._X = self._ed25519.get_public_key(self._x)

        self._B = b64decode(self._onion_router.key_ntor.encode())

        # and generates a client-side handshake with contents:
        #     NODE_ID     Server identity digest  [ID_LENGTH bytes]
        #     KEYID       KEYID(B)                [H_LENGTH bytes]
        #     CLIENT_PK   X                       [G_LENGTH bytes]
        self._handshake = b16decode(self._onion_router.identity.encode())
        self._handshake += self._B
        self._handshake += self._X 
Example 3
Project: Fluid-Designer   Author: Microvellum   File: test_base64.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_b16decode(self):
        eq = self.assertEqual
        eq(base64.b16decode(b'0102ABCDEF'), b'\x01\x02\xab\xcd\xef')
        eq(base64.b16decode('0102ABCDEF'), b'\x01\x02\xab\xcd\xef')
        eq(base64.b16decode(b'00'), b'\x00')
        eq(base64.b16decode('00'), b'\x00')
        # Lower case is not allowed without a flag
        self.assertRaises(binascii.Error, base64.b16decode, b'0102abcdef')
        self.assertRaises(binascii.Error, base64.b16decode, '0102abcdef')
        # Case fold
        eq(base64.b16decode(b'0102abcdef', True), b'\x01\x02\xab\xcd\xef')
        eq(base64.b16decode('0102abcdef', True), b'\x01\x02\xab\xcd\xef')
        # Non-bytes
        self.check_other_types(base64.b16decode, b"0102ABCDEF",
                               b'\x01\x02\xab\xcd\xef')
        self.check_decode_type_errors(base64.b16decode)
        eq(base64.b16decode(bytearray(b"0102abcdef"), True),
           b'\x01\x02\xab\xcd\xef')
        eq(base64.b16decode(memoryview(b"0102abcdef"), True),
           b'\x01\x02\xab\xcd\xef')
        eq(base64.b16decode(array('B', b"0102abcdef"), True),
           b'\x01\x02\xab\xcd\xef') 
Example 4
Project: ironpython3   Author: IronLanguages   File: test_base64.py    License: Apache License 2.0 6 votes vote down vote up
def test_b16decode(self):
        eq = self.assertEqual
        eq(base64.b16decode(b'0102ABCDEF'), b'\x01\x02\xab\xcd\xef')
        eq(base64.b16decode('0102ABCDEF'), b'\x01\x02\xab\xcd\xef')
        eq(base64.b16decode(b'00'), b'\x00')
        eq(base64.b16decode('00'), b'\x00')
        # Lower case is not allowed without a flag
        self.assertRaises(binascii.Error, base64.b16decode, b'0102abcdef')
        self.assertRaises(binascii.Error, base64.b16decode, '0102abcdef')
        # Case fold
        eq(base64.b16decode(b'0102abcdef', True), b'\x01\x02\xab\xcd\xef')
        eq(base64.b16decode('0102abcdef', True), b'\x01\x02\xab\xcd\xef')
        # Non-bytes
        self.check_other_types(base64.b16decode, b"0102ABCDEF",
                               b'\x01\x02\xab\xcd\xef')
        self.check_decode_type_errors(base64.b16decode)
        eq(base64.b16decode(bytearray(b"0102abcdef"), True),
           b'\x01\x02\xab\xcd\xef')
        eq(base64.b16decode(memoryview(b"0102abcdef"), True),
           b'\x01\x02\xab\xcd\xef')
        eq(base64.b16decode(array('B', b"0102abcdef"), True),
           b'\x01\x02\xab\xcd\xef') 
Example 5
Project: dfvfs   Author: log2timeline   File: base16_decoder.py    License: Apache License 2.0 6 votes vote down vote up
def Decode(self, encoded_data):
    """Decode the encoded data.

    Args:
      encoded_data (byte): encoded data.

    Returns:
      tuple(bytes, bytes): decoded data and remaining encoded data.

    Raises:
      BackEndError: if the base16 stream cannot be decoded.
    """
    try:
      decoded_data = base64.b16decode(encoded_data, casefold=False)
    except (TypeError, binascii.Error) as exception:
      raise errors.BackEndError(
          'Unable to decode base16 stream with error: {0!s}.'.format(
              exception))

    return decoded_data, b'' 
Example 6
Project: dj-spam   Author: pydanny   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def b16_slug_to_arguments(b16_slug):
    """

        Raises B16DecodingFail exception on
    """
    try:
        url = b16decode(b16_slug.decode('utf-8'))
    except BinaryError:
        raise B16DecodingFail
    except TypeError:
        raise B16DecodingFail('Non-base16 digit found')
    except AttributeError:
        raise B16DecodingFail("b16_slug must have a 'decode' method.")

    try:
        app, model, pk = url.decode('utf-8').split('/')[0:3]
    except UnicodeDecodeError:
        raise B16DecodingFail("Invalid b16_slug passed")
    return app, model, pk 
Example 7
Project: XFLTReaT   Author: earthquake   File: encoding.py    License: MIT License 5 votes vote down vote up
def decode(self, text):
		try:
			return base64.b16decode(text.upper())
		except:
			return "" 
Example 8
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 9
Project: ironpython2   Author: IronLanguages   File: audiotests.py    License: Apache License 2.0 5 votes vote down vote up
def fromhex(s):
    return base64.b16decode(s.replace(' ', '')) 
Example 10
Project: ironpython2   Author: IronLanguages   File: test_base64.py    License: Apache License 2.0 5 votes vote down vote up
def test_b16decode(self):
        eq = self.assertEqual
        eq(base64.b16decode('0102ABCDEF'), '\x01\x02\xab\xcd\xef')
        eq(base64.b16decode('00'), '\x00')
        # Lower case is not allowed without a flag
        self.assertRaises(TypeError, base64.b16decode, '0102abcdef')
        # Case fold
        eq(base64.b16decode('0102abcdef', True), '\x01\x02\xab\xcd\xef')
        # Non-bytes
        eq(base64.b16decode(bytearray("0102ABCDEF")), '\x01\x02\xab\xcd\xef')
        # Non-alphabet characters
        self.assertRaises(TypeError, base64.b16decode, '0102AG')
        # Incorrect "padding"
        self.assertRaises(TypeError, base64.b16decode, '010') 
Example 11
def _base16_decode(self, decode_string):
        decoder = base64.b16decode(decode_string, casefol=False)
        return decoder 
Example 12
Project: django-more   Author: ashleywaite   File: hashing.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def b64from16(val):
    """ ASCII encoded base 64 string from a base 16 digest """
    return b64from256(b16decode(val, casefold=True)) 
Example 13
Project: BinderFilter   Author: dxwu   File: test_base64.py    License: MIT License 5 votes vote down vote up
def test_b16decode(self):
        eq = self.assertEqual
        eq(base64.b16decode('0102ABCDEF'), '\x01\x02\xab\xcd\xef')
        eq(base64.b16decode('00'), '\x00')
        # Lower case is not allowed without a flag
        self.assertRaises(TypeError, base64.b16decode, '0102abcdef')
        # Case fold
        eq(base64.b16decode('0102abcdef', True), '\x01\x02\xab\xcd\xef')
        # Non-bytes
        eq(base64.b16decode(bytearray("0102ABCDEF")), '\x01\x02\xab\xcd\xef') 
Example 14
Project: python_dhcp_server   Author: niccokunzmann   File: listener.py    License: MIT License 5 votes vote down vote up
def macpack(mac):
    return base64.b16decode(mac.replace(':', '').replace('-', '').encode('ascii')) 
Example 15
Project: oss-ftp   Author: aliyun   File: audiotests.py    License: MIT License 5 votes vote down vote up
def fromhex(s):
    return base64.b16decode(s.replace(' ', '')) 
Example 16
Project: oss-ftp   Author: aliyun   File: test_base64.py    License: MIT License 5 votes vote down vote up
def test_b16decode(self):
        eq = self.assertEqual
        eq(base64.b16decode('0102ABCDEF'), '\x01\x02\xab\xcd\xef')
        eq(base64.b16decode('00'), '\x00')
        # Lower case is not allowed without a flag
        self.assertRaises(TypeError, base64.b16decode, '0102abcdef')
        # Case fold
        eq(base64.b16decode('0102abcdef', True), '\x01\x02\xab\xcd\xef')
        # Non-bytes
        eq(base64.b16decode(bytearray("0102ABCDEF")), '\x01\x02\xab\xcd\xef') 
Example 17
Project: warcio   Author: webrecorder   File: digestverifyingreader.py    License: Apache License 2.0 5 votes vote down vote up
def _to_b32(length, value):
    '''
    Convert value to base 32, given that it's supposed to have the same
    length as the digest we're about to compare it to
    '''
    if len(value) == length:
        return value  # casefold needed here? -- rfc recommends not allowing

    if len(value) > length:
        binary = base64.b16decode(value, casefold=True)
    else:
        binary = _b64_wrapper(value)

    return to_native_str(base64.b32encode(binary), encoding='ascii') 
Example 18
Project: Python   Author: TheAlgorithms   File: base16.py    License: MIT License 5 votes vote down vote up
def main():
    inp = input("->")
    encoded = inp.encode("utf-8")  # encoded the input (we need a bytes like object)
    b16encoded = base64.b16encode(encoded)  # b16encoded the encoded string
    print(b16encoded)
    print(base64.b16decode(b16encoded).decode("utf-8"))  # decoded it 
Example 19
Project: TinyTor   Author: Marten4n6   File: tinytor.py    License: GNU General Public License v3.0 5 votes vote down vote up
def complete_handshake(self, Y, auth):
        """
        :type Y: bytes
        :type auth: bytes

        The server's handshake reply is:
            SERVER_PK   Y                       [G_LENGTH bytes]
            AUTH        H(auth_input, t_mac)    [H_LENGTH bytes]

        Updates the onion router's shared secret with the computed key.
        """
        # The client then checks Y is in G^* [see NOTE below], and computes
        # secret_input = EXP(Y,x) | EXP(B,x) | ID | B | X | Y | PROTOID
        secret_input = self._ed25519.smult_curve25519(self._x, Y)
        secret_input += self._ed25519.smult_curve25519(self._x, self._B)
        secret_input += b16decode(self._onion_router.identity.encode())
        secret_input += self._B
        secret_input += self._X
        secret_input += Y
        secret_input += b'ntor-curve25519-sha256-1'

        # KEY_SEED = H(secret_input, t_key) -- Not used.
        # verify = H(secret_input, t_verify)
        verify = self._hmac_sha256(KeyAgreementNTOR.t_verify, secret_input)

        # auth_input = verify | ID | B | Y | X | PROTOID | "Server"
        auth_input = verify
        auth_input += b16decode(self._onion_router.identity.encode())
        auth_input += self._B
        auth_input += Y
        auth_input += self._X
        auth_input += KeyAgreementNTOR.PROTOCOL_ID
        auth_input += b'Server'

        # The client verifies that AUTH == H(auth_input, t_mac).
        if auth != self._hmac_sha256(KeyAgreementNTOR.t_mac, auth_input):
            log.error("Server handshake doesn't match verification")
            raise Exception("Server handshake doesn't match verificaiton.")

        self._onion_router.set_shared_secret(self._kdf_rfc5869(secret_input, 72))
        log.debug("Handshake verified, onion router's shared secret has been set.") 
Example 20
Project: shellsploit-library   Author: riusksk   File: encryption.py    License: MIT License 5 votes vote down vote up
def base16(TEXT, choice):
    from base64 import b16encode, b16decode
    return b16encode(TEXT.encode('utf-8')).decode('utf-8') if choice == "encode" else b16decode(TEXT).decode("utf-8") 
Example 21
Project: hacker-scripts   Author: restran   File: what_encode.py    License: MIT License 5 votes vote down vote up
def parse_str(encode_str, decode_method, *args, **kwargs):
    if len(encode_str) == 0:
        return False, encode_str

    try:
        if decode_method == 'base16':
            decode_str = b16decode(encode_str)
        elif decode_method == 'base32':
            decode_str = b32decode(encode_str)
        elif decode_method == 'binary':
            tmp = encode_str.replace('0', '').replace('1', '').strip()
            if tmp == '':
                # 解码后是 0xab1234,需要去掉前面的 0x
                decode_str = hex(int(encode_str, 2))[2:].rstrip('L')
            else:
                return False, encode_str
        else:
            decode_str = encode_str.decode(decode_method)
        # logger.info('%s: %s' % (decode_method, decode_str))
        if len(decode_str) == 0:
            return False, encode_str
        else:
            return True, decode_str
    except Exception as e:
        # print(e)
        return False, encode_str 
Example 22
Project: zulip   Author: zulip   File: upload.py    License: Apache License 2.0 5 votes vote down vote up
def get_local_file_path_id_from_token(token: str) -> Optional[str]:
    signer = TimestampSigner(salt=LOCAL_FILE_ACCESS_TOKEN_SALT)
    try:
        signed_data = base64.b16decode(token).decode('utf-8')
        path_id = signer.unsign(signed_data, max_age=timedelta(seconds=60))
    except (BadSignature, binascii.Error):
        return None

    return path_id 
Example 23
Project: outis   Author: SySS-Research   File: encoding.py    License: MIT License 5 votes vote down vote up
def dnshostdecode(data):
    """
    decodes DNS transmittable hostname data, 0-9A-F, ignoring casing
    :param data: DNS transmittable hostname data
    :return: decoded form
    """

    # TODO: receiving 0-9A-Z would be better
    return base64.b16decode(data, casefold=True) 
Example 24
Project: Fluid-Designer   Author: Microvellum   File: test_base64.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_decode_nonascii_str(self):
        decode_funcs = (base64.b64decode,
                        base64.standard_b64decode,
                        base64.urlsafe_b64decode,
                        base64.b32decode,
                        base64.b16decode,
                        base64.b85decode,
                        base64.a85decode)
        for f in decode_funcs:
            self.assertRaises(ValueError, f, 'with non-ascii \xcb') 
Example 25
Project: ironpython3   Author: IronLanguages   File: test_base64.py    License: Apache License 2.0 5 votes vote down vote up
def test_decode_nonascii_str(self):
        decode_funcs = (base64.b64decode,
                        base64.standard_b64decode,
                        base64.urlsafe_b64decode,
                        base64.b32decode,
                        base64.b16decode,
                        base64.b85decode,
                        base64.a85decode)
        for f in decode_funcs:
            self.assertRaises(ValueError, f, 'with non-ascii \xcb') 
Example 26
Project: programming-challenges   Author: anomen-s   File: solve.py    License: GNU General Public License v2.0 5 votes vote down vote up
def hex2b64(s):
    '''
     Convert hex string to string
    '''
    #asBytes = bytes.fromhex(s)
    asBytes = base64.b16decode(STR.upper())
    asB64 = base64.b64encode(asBytes)
    return str(asB64, 'utf-8') 
Example 27
Project: pysunspec   Author: sunspec   File: util.py    License: MIT License 5 votes vote down vote up
def ipv6addr_to_data(addr, slen=None):
    s = base64.b16decode(addr.replace(':', ''))
    if slen is None:
        slen = len(s)
    return struct.pack(str(slen) + 's', s) 
Example 28
Project: pysunspec   Author: sunspec   File: util.py    License: MIT License 5 votes vote down vote up
def eui48_to_data(eui48):
    return (b'\x00\x00' + base64.b16decode(eui48.replace(':', ''))) 
Example 29
Project: gcblue   Author: gcblue   File: audiotests.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def fromhex(s):
    return base64.b16decode(s.replace(' ', '')) 
Example 30
Project: gcblue   Author: gcblue   File: test_base64.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_b16decode(self):
        eq = self.assertEqual
        eq(base64.b16decode('0102ABCDEF'), '\x01\x02\xab\xcd\xef')
        eq(base64.b16decode('00'), '\x00')
        # Lower case is not allowed without a flag
        self.assertRaises(TypeError, base64.b16decode, '0102abcdef')
        # Case fold
        eq(base64.b16decode('0102abcdef', True), '\x01\x02\xab\xcd\xef')
        # Non-bytes
        eq(base64.b16decode(bytearray("0102ABCDEF")), '\x01\x02\xab\xcd\xef')