Python base64.b16decode() Examples

The following are 30 code examples of base64.b16decode(). 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 base64 , or try the search function .
Example #1
Source File: test_base64.py    From ironpython3 with 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 #2
Source File: base16_decoder.py    From dfvfs with 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 #3
Source File: utils.py    From dj-spam with 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 #4
Source File: test_base64.py    From Fluid-Designer with 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 #5
Source File: tinytor.py    From TinyTor with 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 #6
Source File: templates.py    From king-phisher with 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 #7
Source File: choreography_test.py    From pynab with GNU General Public License v3.0 5 votes vote down vote up
def test_set_leds_color(self):
        chor = base64.b16decode("0009020304")
        task = self.loop.create_task(self.ci.play_binary(chor))
        self.loop.run_until_complete(task)
        self.assertEqual(self.leds.called_list, ["setall(2,3,4)"])
        self.assertEqual(self.ears.called_list, [])
        self.assertEqual(self.sound.called_list, []) 
Example #8
Source File: test_base64.py    From android_universal with MIT License 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 #9
Source File: test_base64.py    From android_universal with MIT License 5 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')
        # Non-alphabet characters
        self.assertRaises(binascii.Error, base64.b16decode, '0102AG')
        # Incorrect "padding"
        self.assertRaises(binascii.Error, base64.b16decode, '010') 
Example #10
Source File: choreography_test.py    From pynab with GNU General Public License v3.0 5 votes vote down vote up
def test_set_motor(self):
        chor = base64.b16decode("0008010300")
        task = self.loop.create_task(self.ci.play_binary(chor))
        self.loop.run_until_complete(task)
        self.assertEqual(self.leds.called_list, [])
        self.assertEqual(self.ears.called_list, ["go(1,3,0)"])
        self.assertEqual(self.sound.called_list, []) 
Example #11
Source File: __init__.py    From vulners-agent with MIT License 5 votes vote down vote up
def __decode_data(self, encoded_data):
        try:
            data = json.loads(base64.b16decode(zlib.decompress(encoded_data)))
        except Exception as exc:
            self.log.exception("Problems decoding data file %s" % exc)
            return {}
        return data 
Example #12
Source File: testpkey.py    From ctypescrypto with MIT License 5 votes vote down vote up
def test_sign(self):
        signer=PKey(privkey=self.ec1priv)
        digest=b16decode("FFCA2587CFD4846E4CB975B503C9EB940F94566AA394E8BD571458B9DA5097D5")
        signature=signer.sign(digest)
        self.assertTrue(len(signature)>0)
        verifier=PKey(pubkey=self.ec1pub)
        self.assertTrue(verifier.verify(digest,signature)) 
Example #13
Source File: choreography_test.py    From pynab with GNU General Public License v3.0 5 votes vote down vote up
def test_set_led_color(self):
        chor = base64.b16decode("0007020304050607")
        task = self.loop.create_task(self.ci.play_binary(chor))
        self.loop.run_until_complete(task)
        self.assertEqual(self.leds.called_list, ["set1(Led.CENTER,3,4,5)"])
        self.assertEqual(self.ears.called_list, [])
        self.assertEqual(self.sound.called_list, []) 
Example #14
Source File: javascriptUtils.py    From filmkodi with Apache License 2.0 5 votes vote down vote up
def UnPPAll(self,data):
        def removeNonAscii(s): return "".join(i for i in s if ord(i)<128)
        
        in_data = data
        tPattern = r"var\s*t=['\"](\w+)['\"]\s*;\s*for"
        
        t_data = re.compile(tPattern).findall(in_data)
        
        for i in t_data:
            out_data = removeNonAscii(str(base64.b16decode(i.upper())))
            data = re.sub(r"var\s*t=\"[^}]+}", out_data, data, count=1)
                
        return data 
Example #15
Source File: choreography_test.py    From pynab with GNU General Public License v3.0 5 votes vote down vote up
def test_set_led_off(self):
        chor = base64.b16decode("000A02")
        task = self.loop.create_task(self.ci.play_binary(chor))
        self.loop.run_until_complete(task)
        self.assertEqual(self.leds.called_list, ["set1(Led.CENTER,0,0,0)"])
        self.assertEqual(self.ears.called_list, [])
        self.assertEqual(self.sound.called_list, []) 
Example #16
Source File: testec.py    From ctypescrypto with MIT License 5 votes vote down vote up
def test_keyone(self):
        key=create(Oid("secp256k1"),b16decode("2A71BA9DEA99BC1F7C104BAEC671EC7EFF8BFF969BB8D346DB4C3352A4699DC3",True))
            
        out=key.exportpriv()
        if pyver > 2:
            out=out.encode("ascii")
        self.assertEqual(dump_key(out),dump_key(self.ec1priv))
        if pyver == 2:
            self.assertEqual(str(key),dump_pub_key(self.ec1priv))
        else:    
            self.assertEqual(str(key).encode("ascii"),dump_pub_key(self.ec1priv)) 
Example #17
Source File: test_base64.py    From gcblue with 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') 
Example #18
Source File: encoding.py    From OpenBazaar-Installer with MIT License 5 votes vote down vote up
def decode(data):
        return base64.b16decode(data) 
Example #19
Source File: encoding.py    From OpenBazaar-Installer with MIT License 5 votes vote down vote up
def decode(data):
        return base64.b16decode(data) 
Example #20
Source File: test_base64.py    From medicare-demo with 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') 
Example #21
Source File: test_base64.py    From Project-New-Reign---Nemesis-Main with 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 #22
Source File: test_base64.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 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')
        # Non-alphabet characters
        self.assertRaises(binascii.Error, base64.b16decode, '0102AG')
        # Incorrect "padding"
        self.assertRaises(binascii.Error, base64.b16decode, '010') 
Example #23
Source File: validator_utils.py    From Decentralized-Internet with MIT License 5 votes vote down vote up
def get_public_key_decoder(pk):
    encoding = pk['type']
    decoder = base64.b64decode

    if encoding == 'ed25519-base16':
        decoder = base64.b16decode
    elif encoding == 'ed25519-base32':
        decoder = base64.b32decode
    elif encoding == 'ed25519-base64':
        decoder = base64.b64decode
    else:
        raise InvalidPublicKey('Invalid `type` specified for public key `value`')

    return decoder 
Example #24
Source File: validator_utils.py    From Decentralized-Internet with MIT License 5 votes vote down vote up
def get_public_key_decoder(pk):
    encoding = pk['type']
    decoder = base64.b64decode

    if encoding == 'ed25519-base16':
        decoder = base64.b16decode
    elif encoding == 'ed25519-base32':
        decoder = base64.b32decode
    elif encoding == 'ed25519-base64':
        decoder = base64.b64decode
    else:
        raise InvalidPublicKey('Invalid `type` specified for public key `value`')

    return decoder 
Example #25
Source File: validator_utils.py    From bigchaindb with Apache License 2.0 5 votes vote down vote up
def get_public_key_decoder(pk):
    encoding = pk['type']
    decoder = base64.b64decode

    if encoding == 'ed25519-base16':
        decoder = base64.b16decode
    elif encoding == 'ed25519-base32':
        decoder = base64.b32decode
    elif encoding == 'ed25519-base64':
        decoder = base64.b64decode
    else:
        raise InvalidPublicKey('Invalid `type` specified for public key `value`')

    return decoder 
Example #26
Source File: objects.py    From pydal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def retrieve_file_properties(self, name, path=None):
        m = re.match(REGEX_UPLOAD_PATTERN, name)
        if not m or not self.isattachment:
            raise TypeError("Can't retrieve %s file properties" % name)
        self_uploadfield = self.uploadfield
        if self.custom_retrieve_file_properties:
            return self.custom_retrieve_file_properties(name, path)
        if m.group("name"):
            try:
                filename = base64.b16decode(m.group("name"), True).decode("utf-8")
                filename = re.sub(REGEX_UPLOAD_CLEANUP, "_", filename)
            except (TypeError, AttributeError, binascii.Error):
                filename = name
        else:
            filename = name
        # ## if file is in DB
        if isinstance(self_uploadfield, (str, Field)):
            return dict(path=None, filename=filename)
        # ## if file is on filesystem
        if not path:
            if self.uploadfolder:
                path = self.uploadfolder
            else:
                path = pjoin(self.db._adapter.folder, "..", "uploads")
        if self.uploadseparate:
            t = m.group("table")
            f = m.group("field")
            u = m.group("uuidkey")
            path = pjoin(path, "%s.%s" % (t, f), u[:2])
        return dict(path=path, filename=filename) 
Example #27
Source File: compute_response.py    From komodo-wakatime with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_channel_bindings_value(server_certificate_hash):
        """
        https://msdn.microsoft.com/en-us/library/windows/desktop/dd919963%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
        https://blogs.msdn.microsoft.com/openspecification/2013/03/26/ntlm-and-channel-binding-hash-aka-extended-protection-for-authentication/

        Get's the MD5 hash of the gss_channel_bindings_struct to add to the AV_PAIR MSV_AV_CHANNEL_BINDINGS.
        This method takes in the SHA256 hash (Hash of the DER encoded certificate of the server we are connecting to)
        and add's it to the gss_channel_bindings_struct. It then gets the MD5 hash and converts this to a
        byte array in preparation of adding it to the AV_PAIR structure.

        :param server_certificate_hash: The SHA256 hash of the server certificate (DER encoded) NTLM is authenticated to
        :return channel_bindings: An MD5 hash of the gss_channel_bindings_struct to add to the AV_PAIR MsvChannelBindings
        """
        # Channel Binding Tokens support, used for NTLMv2
        # Decode the SHA256 certificate hash
        certificate_digest = base64.b16decode(server_certificate_hash)

        # Initialise the GssChannelBindingsStruct and add the certificate_digest to the application_data field
        gss_channel_bindings = GssChannelBindingsStruct()
        gss_channel_bindings[gss_channel_bindings.APPLICATION_DATA] = 'tls-server-end-point:'.encode() + certificate_digest

        # Get the gss_channel_bindings_struct and create an MD5 hash
        channel_bindings_struct_data = gss_channel_bindings.get_data()
        channel_bindings_hash = hashlib.md5(channel_bindings_struct_data).hexdigest()

        try:
            cbt_value = bytearray.fromhex(channel_bindings_hash)
        except TypeError:
            # Work-around for Python 2.6 bug
            cbt_value = bytearray.fromhex(unicode(channel_bindings_hash))

        channel_bindings = bytes(cbt_value)
        return channel_bindings 
Example #28
Source File: application.py    From python-app-sdk with MIT License 5 votes vote down vote up
def __lorawanDeviceRequest(self, dev_id, device, update=False):
        if update:
            req = self.device(dev_id).lorawan_device
        else:
            req = lorawan.Device()
        req.app_id = self.app_id
        req.dev_id = dev_id

        if "appEui" in device:
            req.app_eui = base64.b16decode(device["appEui"])

        if "devEui" in device:
            req.dev_eui = base64.b16decode(device["devEui"])

        if "devAddr" in device:
            req.dev_addr = base64.b16decode(device["devAddr"])

        if "nwkSKey" in device:
            req.nwk_s_key = base64.b16decode(device["nwkSKey"])

        if "appSKey" in device:
            req.app_s_key = base64.b16decode(device["appSKey"])

        if "appKey" in device:
            req.app_key = base64.b16decode(device["appKey"])

        if "fCntUp" in device:
            req.f_cnt_up = device["fCntUp"]

        if "fCntDown" in device:
            req.f_cnt_down = device["fCntDown"]

        if "disableFCntCheck" in device:
            req.disable_f_cnt_check = device["disableFCntCheck"]

        if "uses32BitFCnt" in device:
            req.uses32_bit_f_cnt = device["uses32BitFCnt"]

        return req 
Example #29
Source File: encoding.py    From XFLTReaT with MIT License 5 votes vote down vote up
def decode(self, text):
		try:
			return base64.b16decode(text.upper())
		except:
			return "" 
Example #30
Source File: encode.py    From libnacl with Apache License 2.0 5 votes vote down vote up
def base16_decode(data):
    '''
    Base16 decode data
    '''
    return base64.b16decode(data)