Python base64.b85encode() Examples

The following are 26 code examples of base64.b85encode(). 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_plugins.py    From deen with Apache License 2.0 6 votes vote down vote up
def test_decode_base85(self):
        if sys.version_info.major != 3 or \
                sys.version_info.minor < 4:
            self.fail('Base85 support not available for the current Python version!')
        data_bytes = self._random_bytes()
        encoded_bytes = base64.b85encode(data_bytes)
        plugin = self._plugins.get_plugin_instance('base85')
        result = plugin.unprocess(encoded_bytes)
        self.assertIsNone(plugin.error), 'An error occurred during Base85 decoding'
        self.assertIsInstance(result, bytes,
            'Base85 decoding result should be bytes or bytearray, '
            'got %s instead' % type(result))
        self.assertEqual(data_bytes, result)
        data_str = self._random_str()
        self.assertRaises(TypeError, functools.partial(
            plugin.unprocess, data_str), 'Unexpected exception raised') 
Example #2
Source File: test_plugins.py    From deen with Apache License 2.0 6 votes vote down vote up
def test_encode_base85(self):
        if sys.version_info.major != 3 or \
                sys.version_info.minor < 4:
            self.fail('Base85 support not available for the current Python version!')
        data_bytes = self._random_bytes()
        encoded_bytes = base64.b85encode(data_bytes)
        plugin = self._plugins.get_plugin_instance('base85')
        result = plugin.process(data_bytes)
        self.assertIsNone(plugin.error), 'An error occurred during Base85 encoding'
        self.assertIsInstance(result, bytes,
            'Base85 encoding result should be bytes or bytearray, '
            'got %s instead' % type(result))
        self.assertEqual(encoded_bytes, result)
        data_str = self._random_str()
        self.assertRaises(TypeError, functools.partial(
            plugin.process, data_str), 'Unexpected exception raised') 
Example #3
Source File: pyzlibaes.py    From vrequest with 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
Source File: handlers.py    From agents-aea with Apache License 2.0 6 votes vote down vote up
def send_decoding_error(self, envelope: Envelope) -> None:
        """
        Handle a decoding error.

        :param envelope: the envelope
        :return: None
        """
        self.context.logger.warning(
            "Decoding error for envelope: {}. Protocol_id='{}' and message='{!r}' are inconsistent.".format(
                envelope, envelope.protocol_id, envelope.message
            )
        )
        encoded_envelope = base64.b85encode(envelope.encode())
        reply = DefaultMessage(
            dialogue_reference=("", ""),
            message_id=1,
            target=0,
            performative=DefaultMessage.Performative.ERROR,
            error_code=DefaultMessage.ErrorCode.DECODING_ERROR,
            error_msg="Decoding error.",
            error_data={"envelope": encoded_envelope},
        )
        reply.counterparty = envelope.sender
        self.context.outbox.put_message(message=reply) 
Example #5
Source File: handlers.py    From agents-aea with Apache License 2.0 6 votes vote down vote up
def send_decoding_error(self, envelope: Envelope) -> None:
        """
        Handle a decoding error.

        :param envelope: the envelope
        :return: None
        """
        self.context.logger.warning(
            "Decoding error for envelope: {}. Protocol_id='{}' and message='{!r}' are inconsistent.".format(
                envelope, envelope.protocol_id, envelope.message
            )
        )
        encoded_envelope = base64.b85encode(envelope.encode())
        reply = DefaultMessage(
            dialogue_reference=("", ""),
            message_id=1,
            target=0,
            performative=DefaultMessage.Performative.ERROR,
            error_code=DefaultMessage.ErrorCode.DECODING_ERROR,
            error_msg="Decoding error.",
            error_data={"envelope": encoded_envelope},
        )
        reply.counterparty = envelope.sender
        self.context.outbox.put_message(message=reply) 
Example #6
Source File: handlers.py    From agents-aea with Apache License 2.0 5 votes vote down vote up
def send_unsupported_protocol(self, envelope: Envelope) -> None:
        """
        Handle the received envelope in case the protocol is not supported.

        :param envelope: the envelope
        :return: None
        """
        self.context.logger.warning(
            "Unsupported protocol: {}. You might want to add a handler for this protocol.".format(
                envelope.protocol_id
            )
        )
        encoded_protocol_id = base64.b85encode(str.encode(str(envelope.protocol_id)))
        encoded_envelope = base64.b85encode(envelope.encode())
        reply = DefaultMessage(
            dialogue_reference=("", ""),
            message_id=1,
            target=0,
            performative=DefaultMessage.Performative.ERROR,
            error_code=DefaultMessage.ErrorCode.UNSUPPORTED_PROTOCOL,
            error_msg="Unsupported protocol.",
            error_data={
                "protocol_id": encoded_protocol_id,
                "envelope": encoded_envelope,
            },
        )
        reply.counterparty = envelope.sender
        self.context.outbox.put_message(message=reply) 
Example #7
Source File: test_base64.py    From android_universal with MIT License 5 votes vote down vote up
def test_b85_padding(self):
        eq = self.assertEqual

        eq(base64.b85encode(b"x", pad=True), b'cmMzZ')
        eq(base64.b85encode(b"xx", pad=True), b'cz6H+')
        eq(base64.b85encode(b"xxx", pad=True), b'czAdK')
        eq(base64.b85encode(b"xxxx", pad=True), b'czAet')
        eq(base64.b85encode(b"xxxxx", pad=True), b'czAetcmMzZ')

        eq(base64.b85decode(b'cmMzZ'), b"x\x00\x00\x00")
        eq(base64.b85decode(b'cz6H+'), b"xx\x00\x00")
        eq(base64.b85decode(b'czAdK'), b"xxx\x00")
        eq(base64.b85decode(b'czAet'), b"xxxx")
        eq(base64.b85decode(b'czAetcmMzZ'), b"xxxxx\x00\x00\x00") 
Example #8
Source File: test_base64.py    From android_universal with MIT License 5 votes vote down vote up
def test_b85encode(self):
        eq = self.assertEqual

        tests = {
            b'': b'',
            b'www.python.org': b'cXxL#aCvlSZ*DGca%T',
            bytes(range(255)): b"""009C61O)~M2nh-c3=Iws5D^j+6crX17#SKH9337X"""
                b"""AR!_nBqb&%C@Cr{EG;fCFflSSG&MFiI5|2yJUu=?KtV!7L`6nNNJ&ad"""
                b"""OifNtP*GA-R8>}2SXo+ITwPvYU}0ioWMyV&XlZI|Y;A6DaB*^Tbai%j"""
                b"""czJqze0_d@fPsR8goTEOh>41ejE#<ukdcy;l$Dm3n3<ZJoSmMZprN9p"""
                b"""q@|{(sHv)}tgWuEu(7hUw6(UkxVgH!yuH4^z`?@9#Kp$P$jQpf%+1cv"""
                b"""(9zP<)YaD4*xB0K+}+;a;Njxq<mKk)=;`X~?CtLF@bU8V^!4`l`1$(#"""
                b"""{Qdp""",
            b"""abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"""
                b"""0123456789!@#0^&*();:<>,. []{}""":
                b"""VPa!sWoBn+X=-b1ZEkOHadLBXb#`}nd3r%YLqtVJM@UIZOH55pPf$@("""
                b"""Q&d$}S6EqEFflSSG&MFiI5{CeBQRbjDkv#CIy^osE+AW7dwl""",
            b'no padding..': b'Zf_uPVPs@!Zf7no',
            b'zero compression\x00\x00\x00\x00': b'dS!BNAY*TBaB^jHb7^mG00000',
            b'zero compression\x00\x00\x00': b'dS!BNAY*TBaB^jHb7^mG0000',
            b"""Boundary:\x00\x00\x00\x00""": b"""LT`0$WMOi7IsgCw00""",
            b'Space compr:    ': b'Q*dEpWgug3ZE$irARr(h',
            b'\xff': b'{{',
            b'\xff'*2: b'|Nj',
            b'\xff'*3: b'|Ns9',
            b'\xff'*4: b'|NsC0',
        }

        for data, res in tests.items():
            eq(base64.b85encode(data), res)

        self.check_other_types(base64.b85encode, b"www.python.org",
                               b'cXxL#aCvlSZ*DGca%T') 
Example #9
Source File: plugin_base64.py    From deen with Apache License 2.0 5 votes vote down vote up
def process(self, data):
        super(DeenPluginBase85, self).process(data)
        try:
            data = base64.b85encode(data)
        except Exception as e:
            self.error = e
            self.log.error(self.error)
            self.log.debug(self.error, exc_info=True)
        return data 
Example #10
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_b85_padding(self):
        eq = self.assertEqual

        eq(base64.b85encode(b"x", pad=True), b'cmMzZ')
        eq(base64.b85encode(b"xx", pad=True), b'cz6H+')
        eq(base64.b85encode(b"xxx", pad=True), b'czAdK')
        eq(base64.b85encode(b"xxxx", pad=True), b'czAet')
        eq(base64.b85encode(b"xxxxx", pad=True), b'czAetcmMzZ')

        eq(base64.b85decode(b'cmMzZ'), b"x\x00\x00\x00")
        eq(base64.b85decode(b'cz6H+'), b"xx\x00\x00")
        eq(base64.b85decode(b'czAdK'), b"xxx\x00")
        eq(base64.b85decode(b'czAet'), b"xxxx")
        eq(base64.b85decode(b'czAetcmMzZ'), b"xxxxx\x00\x00\x00") 
Example #11
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_b85encode(self):
        eq = self.assertEqual

        tests = {
            b'': b'',
            b'www.python.org': b'cXxL#aCvlSZ*DGca%T',
            bytes(range(255)): b"""009C61O)~M2nh-c3=Iws5D^j+6crX17#SKH9337X"""
                b"""AR!_nBqb&%C@Cr{EG;fCFflSSG&MFiI5|2yJUu=?KtV!7L`6nNNJ&ad"""
                b"""OifNtP*GA-R8>}2SXo+ITwPvYU}0ioWMyV&XlZI|Y;A6DaB*^Tbai%j"""
                b"""czJqze0_d@fPsR8goTEOh>41ejE#<ukdcy;l$Dm3n3<ZJoSmMZprN9p"""
                b"""q@|{(sHv)}tgWuEu(7hUw6(UkxVgH!yuH4^z`?@9#Kp$P$jQpf%+1cv"""
                b"""(9zP<)YaD4*xB0K+}+;a;Njxq<mKk)=;`X~?CtLF@bU8V^!4`l`1$(#"""
                b"""{Qdp""",
            b"""abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"""
                b"""0123456789!@#0^&*();:<>,. []{}""":
                b"""VPa!sWoBn+X=-b1ZEkOHadLBXb#`}nd3r%YLqtVJM@UIZOH55pPf$@("""
                b"""Q&d$}S6EqEFflSSG&MFiI5{CeBQRbjDkv#CIy^osE+AW7dwl""",
            b'no padding..': b'Zf_uPVPs@!Zf7no',
            b'zero compression\x00\x00\x00\x00': b'dS!BNAY*TBaB^jHb7^mG00000',
            b'zero compression\x00\x00\x00': b'dS!BNAY*TBaB^jHb7^mG0000',
            b"""Boundary:\x00\x00\x00\x00""": b"""LT`0$WMOi7IsgCw00""",
            b'Space compr:    ': b'Q*dEpWgug3ZE$irARr(h',
            b'\xff': b'{{',
            b'\xff'*2: b'|Nj',
            b'\xff'*3: b'|Ns9',
            b'\xff'*4: b'|NsC0',
        }

        for data, res in tests.items():
            eq(base64.b85encode(data), res)

        self.check_other_types(base64.b85encode, b"www.python.org",
                               b'cXxL#aCvlSZ*DGca%T') 
Example #12
Source File: handlers.py    From agents-aea with Apache License 2.0 5 votes vote down vote up
def send_unsupported_protocol(self, envelope: Envelope) -> None:
        """
        Handle the received envelope in case the protocol is not supported.

        :param envelope: the envelope
        :return: None
        """
        self.context.logger.warning(
            "Unsupported protocol: {}. You might want to add a handler for this protocol.".format(
                envelope.protocol_id
            )
        )
        encoded_protocol_id = base64.b85encode(str.encode(str(envelope.protocol_id)))
        encoded_envelope = base64.b85encode(envelope.encode())
        reply = DefaultMessage(
            dialogue_reference=("", ""),
            message_id=1,
            target=0,
            performative=DefaultMessage.Performative.ERROR,
            error_code=DefaultMessage.ErrorCode.UNSUPPORTED_PROTOCOL,
            error_msg="Unsupported protocol.",
            error_data={
                "protocol_id": encoded_protocol_id,
                "envelope": encoded_envelope,
            },
        )
        reply.counterparty = envelope.sender
        self.context.outbox.put_message(message=reply) 
Example #13
Source File: handlers.py    From agents-aea with Apache License 2.0 5 votes vote down vote up
def send_unsupported_skill(self, envelope: Envelope) -> None:
        """
        Handle the received envelope in case the skill is not supported.

        :param envelope: the envelope
        :return: None
        """
        if envelope.skill_id is None:
            self.context.logger.warning(
                "Cannot handle envelope: no active handler registered for the protocol_id='{}'.".format(
                    envelope.protocol_id
                )
            )
        else:
            self.context.logger.warning(
                "Cannot handle envelope: no active handler registered for the protocol_id='{}' and skill_id='{}'.".format(
                    envelope.protocol_id, envelope.skill_id
                )
            )
        encoded_envelope = base64.b85encode(envelope.encode())
        reply = DefaultMessage(
            dialogue_reference=("", ""),
            message_id=1,
            target=0,
            performative=DefaultMessage.Performative.ERROR,
            error_code=DefaultMessage.ErrorCode.UNSUPPORTED_SKILL,
            error_msg="Unsupported skill.",
            error_data={"envelope": encoded_envelope},
        )
        reply.counterparty = envelope.sender
        self.context.outbox.put_message(message=reply) 
Example #14
Source File: encoding.py    From XFLTReaT with MIT License 5 votes vote down vote up
def encode(self, text):
		return base64.b85encode(text).replace("=","") 
Example #15
Source File: util.py    From revscoring with MIT License 5 votes vote down vote up
def dump_observation(observation, f):
    if 'cache' in observation:
        observation['cache'] = \
            str(base64.b85encode(pickle.dumps(observation['cache'])), 'ascii')

    json.dump(observation, f)
    f.write("\n") 
Example #16
Source File: test_base64.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_b85_padding(self):
        eq = self.assertEqual

        eq(base64.b85encode(b"x", pad=True), b'cmMzZ')
        eq(base64.b85encode(b"xx", pad=True), b'cz6H+')
        eq(base64.b85encode(b"xxx", pad=True), b'czAdK')
        eq(base64.b85encode(b"xxxx", pad=True), b'czAet')
        eq(base64.b85encode(b"xxxxx", pad=True), b'czAetcmMzZ')

        eq(base64.b85decode(b'cmMzZ'), b"x\x00\x00\x00")
        eq(base64.b85decode(b'cz6H+'), b"xx\x00\x00")
        eq(base64.b85decode(b'czAdK'), b"xxx\x00")
        eq(base64.b85decode(b'czAet'), b"xxxx")
        eq(base64.b85decode(b'czAetcmMzZ'), b"xxxxx\x00\x00\x00") 
Example #17
Source File: test_base64.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_b85encode(self):
        eq = self.assertEqual

        tests = {
            b'': b'',
            b'www.python.org': b'cXxL#aCvlSZ*DGca%T',
            bytes(range(255)): b"""009C61O)~M2nh-c3=Iws5D^j+6crX17#SKH9337X"""
                b"""AR!_nBqb&%C@Cr{EG;fCFflSSG&MFiI5|2yJUu=?KtV!7L`6nNNJ&ad"""
                b"""OifNtP*GA-R8>}2SXo+ITwPvYU}0ioWMyV&XlZI|Y;A6DaB*^Tbai%j"""
                b"""czJqze0_d@fPsR8goTEOh>41ejE#<ukdcy;l$Dm3n3<ZJoSmMZprN9p"""
                b"""q@|{(sHv)}tgWuEu(7hUw6(UkxVgH!yuH4^z`?@9#Kp$P$jQpf%+1cv"""
                b"""(9zP<)YaD4*xB0K+}+;a;Njxq<mKk)=;`X~?CtLF@bU8V^!4`l`1$(#"""
                b"""{Qdp""",
            b"""abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"""
                b"""0123456789!@#0^&*();:<>,. []{}""":
                b"""VPa!sWoBn+X=-b1ZEkOHadLBXb#`}nd3r%YLqtVJM@UIZOH55pPf$@("""
                b"""Q&d$}S6EqEFflSSG&MFiI5{CeBQRbjDkv#CIy^osE+AW7dwl""",
            b'no padding..': b'Zf_uPVPs@!Zf7no',
            b'zero compression\x00\x00\x00\x00': b'dS!BNAY*TBaB^jHb7^mG00000',
            b'zero compression\x00\x00\x00': b'dS!BNAY*TBaB^jHb7^mG0000',
            b"""Boundary:\x00\x00\x00\x00""": b"""LT`0$WMOi7IsgCw00""",
            b'Space compr:    ': b'Q*dEpWgug3ZE$irARr(h',
            b'\xff': b'{{',
            b'\xff'*2: b'|Nj',
            b'\xff'*3: b'|Ns9',
            b'\xff'*4: b'|NsC0',
        }

        for data, res in tests.items():
            eq(base64.b85encode(data), res)

        self.check_other_types(base64.b85encode, b"www.python.org",
                               b'cXxL#aCvlSZ*DGca%T') 
Example #18
Source File: test_base64.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_b85_padding(self):
        eq = self.assertEqual

        eq(base64.b85encode(b"x", pad=True), b'cmMzZ')
        eq(base64.b85encode(b"xx", pad=True), b'cz6H+')
        eq(base64.b85encode(b"xxx", pad=True), b'czAdK')
        eq(base64.b85encode(b"xxxx", pad=True), b'czAet')
        eq(base64.b85encode(b"xxxxx", pad=True), b'czAetcmMzZ')

        eq(base64.b85decode(b'cmMzZ'), b"x\x00\x00\x00")
        eq(base64.b85decode(b'cz6H+'), b"xx\x00\x00")
        eq(base64.b85decode(b'czAdK'), b"xxx\x00")
        eq(base64.b85decode(b'czAet'), b"xxxx")
        eq(base64.b85decode(b'czAetcmMzZ'), b"xxxxx\x00\x00\x00") 
Example #19
Source File: test_base64.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_b85encode(self):
        eq = self.assertEqual

        tests = {
            b'': b'',
            b'www.python.org': b'cXxL#aCvlSZ*DGca%T',
            bytes(range(255)): b"""009C61O)~M2nh-c3=Iws5D^j+6crX17#SKH9337X"""
                b"""AR!_nBqb&%C@Cr{EG;fCFflSSG&MFiI5|2yJUu=?KtV!7L`6nNNJ&ad"""
                b"""OifNtP*GA-R8>}2SXo+ITwPvYU}0ioWMyV&XlZI|Y;A6DaB*^Tbai%j"""
                b"""czJqze0_d@fPsR8goTEOh>41ejE#<ukdcy;l$Dm3n3<ZJoSmMZprN9p"""
                b"""q@|{(sHv)}tgWuEu(7hUw6(UkxVgH!yuH4^z`?@9#Kp$P$jQpf%+1cv"""
                b"""(9zP<)YaD4*xB0K+}+;a;Njxq<mKk)=;`X~?CtLF@bU8V^!4`l`1$(#"""
                b"""{Qdp""",
            b"""abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"""
                b"""0123456789!@#0^&*();:<>,. []{}""":
                b"""VPa!sWoBn+X=-b1ZEkOHadLBXb#`}nd3r%YLqtVJM@UIZOH55pPf$@("""
                b"""Q&d$}S6EqEFflSSG&MFiI5{CeBQRbjDkv#CIy^osE+AW7dwl""",
            b'no padding..': b'Zf_uPVPs@!Zf7no',
            b'zero compression\x00\x00\x00\x00': b'dS!BNAY*TBaB^jHb7^mG00000',
            b'zero compression\x00\x00\x00': b'dS!BNAY*TBaB^jHb7^mG0000',
            b"""Boundary:\x00\x00\x00\x00""": b"""LT`0$WMOi7IsgCw00""",
            b'Space compr:    ': b'Q*dEpWgug3ZE$irARr(h',
            b'\xff': b'{{',
            b'\xff'*2: b'|Nj',
            b'\xff'*3: b'|Ns9',
            b'\xff'*4: b'|NsC0',
        }

        for data, res in tests.items():
            eq(base64.b85encode(data), res)

        self.check_other_types(base64.b85encode, b"www.python.org",
                               b'cXxL#aCvlSZ*DGca%T') 
Example #20
Source File: encode_lib.py    From dropbox_ext4 with MIT License 5 votes vote down vote up
def main():
    with open(INPUT_FILE, 'rb') as fd:
        contents = fd.read()

    encoded_contents = base64.b85encode(gzip.compress(contents)).decode()

    print("ENCODED_LIB_CONTENTS = (")
    for line in textwrap.wrap(encoded_contents, 128):
        print("    '%s'" % line)
    print(")") 
Example #21
Source File: user.py    From arch-security-tracker with MIT License 5 votes vote down vote up
def hash_password(password, salt):
    hashed = b85encode(shash(password, salt[:User.SALT_LENGTH]))
    return hashed.decode()[:User.PASSWORD_LENGTH] 
Example #22
Source File: user.py    From arch-security-tracker with MIT License 5 votes vote down vote up
def random_string(length=TRACKER_PASSWORD_LENGTH_MIN):
    salt = b85encode(urandom(length))
    return salt.decode() 
Example #23
Source File: imp.py    From bob with GNU General Public License v3.0 5 votes vote down vote up
def packTree(src):
    if not os.path.isdir(src):
        raise BuildError("Cannot import '{}': not a directory!".format(src))

    try:
        f = io.BytesIO()
        with tarfile.open(fileobj=f, mode="w:xz") as tar:
            tar.add(src, arcname=".")
    except OSError as e:
        raise BuildError("Error gathering files: {}".format(str(e)))
    return base64.b85encode(f.getvalue()).decode('ascii') 
Example #24
Source File: _compiler.py    From pyuavcan with MIT License 5 votes vote down vote up
def _pickle_object(x: typing.Any) -> str:
    pck: str = base64.b85encode(gzip.compress(pickle.dumps(x, protocol=4))).decode().strip()
    segment_gen = map(''.join, itertools.zip_longest(*([iter(pck)] * 100), fillvalue=''))
    return '\n'.join(repr(x) for x in segment_gen) 
Example #25
Source File: prepare.py    From PyExfil with MIT License 4 votes vote down vote up
def PrepString(data, max_size=DEFAULT_MAX_PACKET_SIZE, enc_key=DEFAULT_KEY, compress=True):
    '''
    PrepFile creats a file ready for sending and return an object.
    :param data: string, data to be exfiltrated.
    :param max_size: integer, default=6500, max amount of data per packet.
    :param enc_key: string, key for AES encryption. if key is empty string,
                    no encryption will be done. Reduces size of packets.
                    Default key is 'ShutTheFuckUpDonnie!'
    :returns: dictionary with data and 'Packets' as list of packets for
                exfiltration sorted by order.
    '''
    ret = {}
    
    # Compute hashes and other meta data
    hash_raw = hashlib.md5(data).hexdigest()
    if enc_key != "":
        ret['Key'] = enc_key
        ret['EncryptionFlag'] = True
    else:
        ret['EncryptionFlag'] = False
        
    if PY_VER is 3:
        if type(enc_key) is bytes:
            enc_key = enc_key.decode("utf-8")
        if type(data) is bytes:
            data = data.decode("utf-8")
        
    if enc_key is None:
        compData = bytes(data, 'utf-8')
    else:
        compData = rc4(data, enc_key)
    
    if compress:
        compData = zlib.compress(compData)
        compData = base64.b85encode(compData)
    hash_compressed = hashlib.md5(compData).hexdigest()
    ret['FilePath'] = None
    ret['ChunksSize'] = max_size
    ret['FileName'] = None
    ret['RawHash'] = hash_raw
    ret['CompressedHash'] = hash_compressed
    ret['CompressedSize'] = len(compData)
    ret['RawSize'] = len(data)

    packetsData = _splitString(compData, max_size)
    ret['PacketsCount'] = len(packetsData) + 1
    ret['FileSequenceID'] = random.randint(1024,4096)
    ret['Packets'] = packetsData

    return ret 
Example #26
Source File: pycompress.py    From vrequest with MIT License 4 votes vote down vote up
def format_compress(data, base, compress, width, encode, is_file=False):
    if not is_file:
        data = data.encode(encode)
    else:
        import tkinter.filedialog
        file = tkinter.filedialog.askopenfiles()
        if file:
            file = file[0].name
            with open(file, 'rb') as f:
                data = f.read()
        else:
            return ''

    if base == 'base64': _encode, _decode = base64.b64encode, base64.b64decode
    if base == 'base85': _encode, _decode = base64.b85encode, base64.b85decode

    if compress == 'None': zcompress, zdecompress = lambda i:i,                      lambda i:i
    if compress == 'zlib': zcompress, zdecompress = lambda i:zlib.compress(i)[2:-4], lambda i:zlib.decompress(i,-15)
    if compress == 'lzma': zcompress, zdecompress = lambda i:lzma.compress(i),       lambda i:lzma.decompress(i)
    if compress == 'gzip': zcompress, zdecompress = lambda i:gzip.compress(i),       lambda i:gzip.decompress(i)

    if base == 'base64': fbstring = 'zstring = base64.b64decode(zstring)'
    if base == 'base85': fbstring = 'zstring = base64.b85decode(zstring)'
    if compress == 'None': importstring = 'import base64';       fzstring = ''
    if compress == 'zlib': importstring = 'import base64, zlib'; fzstring = 'zstring = zlib.decompress(zstring,-15)'
    if compress == 'lzma': importstring = 'import base64, lzma'; fzstring = 'zstring = lzma.decompress(zstring)'
    if compress == 'gzip': importstring = 'import base64, gzip'; fzstring = 'zstring = gzip.decompress(zstring)'

    if is_file:
        datastring = 'bitdata = zstring\nprint(bitdata[:100])'
    else:
        datastring = 'string = zstring.decode("{}")\nprint(string)'.format(encode)

    zdata = zcompress(data)
    edata = _encode(zdata).decode()
    pack = []
    for idx,i in enumerate(edata,1):
        pack.append(i)
        if idx % width == 0:
            pack.append("'\n'")
    packdata = "'{}'".format(''.join(pack))
    leninfo = '# len(zstring): {}'.format(len(edata))

    return r'''
zstring = (
{}
)

{}
{}
{}{}
{}
'''.format(packdata, leninfo, importstring, fbstring, '\n' + fzstring if fzstring else fzstring, datastring).strip()