def test_a85decode(self): eq = self.assertEqual tests = {b'': b'', b'GB\\6`E-ZP=Df.1GEb>': b'www.python.org', b'! ! * -\'"\n\t\t9eu\r\n7# RL\x0bhG$k3[W&.oNg\'GVB"(`=52*$$(B+<_pR,UFcb-n-Vr/1iJ-0JP==1c70M3&s#]4?Ykm5X@_(6q\'R884cEH9MJ8X:f1+h<)lt#=BSg3>[:ZC?t!MSA7]@cBPD3sCi+\'.E,fo>FEMbNG^4U^I!pHnJ:W<)KS>/9Ll%"IN/`jYOHG]iPa.Q$R$jD4S=Q7DTV8*TUnsrdW2ZetXKAY/Yd(L?[\'d?O\\@K2_]Y2%o^qmn*`5Ta:aN;TJbg"GZd*^:jeCE.%f\\,!5gtgiEi8N\\UjQ5OekiqBum-X60nF?)@o_%qPq"ad`r;HT' : bytes(range(255)), b'@:E_WAS,RgBkhF"D/O92EH6,BF`qtRH$VbC6UX@47n?3D92&&T:Jand;cHat=\'/U/0JP==1c70M3&r-I,;<FN.OZ`-3]oSW/g+A(H[P' : b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#0^&*();:<>,. []{}' , b'DJpY:@:Wn_DJ(RS': b'no padding..', b'H=_,8+Cf>,E,oN2F(oQ1z': b'zero compression\x00\x00\x00\x00', b'H=_,8+Cf>,E,oN2F(oQ1!!!!': b'zero compression\x00\x00\x00', b'6>q!aA79M(3WK-[!!': b'Boundary:\x00\x00\x00\x00', b';fH/TAKYK$D/aMV+<VdL': b'Space compr: ', b'rr': b'\xff', b's8N': b'\xff' * 2, b's8W*': b'\xff' * 3, b's8W-!': b'\xff' * 4} for data, res in tests.items(): eq(base64.a85decode(data), res, data) eq(base64.a85decode(data, adobe=False), res, data) eq(base64.a85decode(data.decode('ascii'), adobe=False), res, data) eq(base64.a85decode(b'<~' + data + b'~>', adobe=True), res, data) eq(base64.a85decode(data + b'~>', adobe=True), res, data) eq(base64.a85decode('<~%s~>' % data.decode('ascii'), adobe=True ), res, data) eq(base64.a85decode(b'yy', foldspaces=True, adobe=False), b' ' * 8) eq(base64.a85decode(b'y+<Vd', foldspaces=True, adobe=False), b' ' * 7) eq(base64.a85decode(b'y+<U', foldspaces=True, adobe=False), b' ' * 6) eq(base64.a85decode(b'y+9', foldspaces=True, adobe=False), b' ' * 5) self.check_other_types(base64.a85decode, b'GB\\6`E-ZP=Df.1GEb>', b'www.python.org')
def pair_faces_in_blocks(): db = get_db() c = db.cursor() c.execute("select count(*) from pairs where distance is null") cnt = c.fetchone()[0] if cnt == 0: return (0, 0) chunk_size = 500 c.execute( """select p.face1, p.face2, f1.encoding, f2.encoding from pairs p inner join faces f1 on p.face1 = f1.id inner join faces f2 on p.face2 = f2.id where distance is null limit ?""", (chunk_size, )) pairs_updates = [] while True: nxt = c.fetchone() if not nxt: break face1, face2, encoding_string1, encoding_string2 = nxt encoding1 = np.fromstring(base64.a85decode(encoding_string1)) encoding2 = np.fromstring(base64.a85decode(encoding_string2)) distance = np.linalg.norm(encoding1 - encoding2) pairs_updates.append({ "face1": face1, "face2": face2, "distance": distance }) c.executemany( "UPDATE pairs SET distance=:distance WHERE face1=:face1 AND face2=:face2", pairs_updates) db.commit() return len(pairs_updates), cnt
def decode(bytes_in: bytes) -> bytes: """ Decodes data encoded in an ASCII base-85 representation """ exceptions_to_throw = [] # trivial case if len(bytes_in) == 0: return bytes_in # trimming if bytes_in[-1] == 10 and bytes_in[-2] == 13: bytes_in = bytes_in[0:-2] if bytes_in[-1] == 10: bytes_in = bytes_in[0:-1] if bytes_in[-1] == 13: bytes_in = bytes_in[0:-1] # normal decode try: return base64.a85decode(bytes_in) except Exception as e: exceptions_to_throw.append(e) pass # adobe decode try: return base64.a85decode(bytes_in, adobe=True) except Exception as e: exceptions_to_throw.append(e) pass # we should not be here raise exceptions_to_throw[0]
def get_private_key(): """ Retrieves my private key from cache or the datastore """ global _PRIVATE_KEY if _PRIVATE_KEY is None: entity = storage.retrieve("config", "bunq_private_key_1") private_1 = base64.a85decode(entity["value"]) entity = storage.retrieve("config", "bunq_private_key_2") private_2 = base64.a85decode(entity["value"]) _PRIVATE_KEY = serialization.load_pem_private_key( private_1 + private_2, password=None, backend=default_backend()) return _PRIVATE_KEY
def test_a85_padding(self): eq = self.assertEqual eq(base64.a85encode(b'x', pad=True), b'GQ7^D') eq(base64.a85encode(b'xx', pad=True), b"G^'2g") eq(base64.a85encode(b'xxx', pad=True), b'G^+H5') eq(base64.a85encode(b'xxxx', pad=True), b'G^+IX') eq(base64.a85encode(b'xxxxx', pad=True), b'G^+IXGQ7^D') eq(base64.a85decode(b'GQ7^D'), b'x\x00\x00\x00') eq(base64.a85decode(b"G^'2g"), b'xx\x00\x00') eq(base64.a85decode(b'G^+H5'), b'xxx\x00') eq(base64.a85decode(b'G^+IX'), b'xxxx') eq(base64.a85decode(b'G^+IXGQ7^D'), b'xxxxx\x00\x00\x00')
def test_a85decode_errors(self): illegal = (set(range(32)) | set(range(118, 256))) - set(b' \t\n\r\x0b') for c in illegal: with self.assertRaises(ValueError, msg=bytes([c])): base64.a85decode(b'!!!!' + bytes([c])) with self.assertRaises(ValueError, msg=bytes([c])): base64.a85decode(b'!!!!' + bytes([c]), adobe=False) with self.assertRaises(ValueError, msg=bytes([c])): base64.a85decode(b'<~!!!!' + bytes([c]) + b'~>', adobe=True) self.assertRaises(ValueError, base64.a85decode, b'malformed', adobe =True) self.assertRaises(ValueError, base64.a85decode, b'<~still malformed', adobe=True) self.assertRaises(ValueError, base64.a85decode, b'<~~>') self.assertRaises(ValueError, base64.a85decode, b'<~~>', adobe=False) base64.a85decode(b'<~~>', adobe=True) self.assertRaises(ValueError, base64.a85decode, b'abcx', adobe=False) self.assertRaises(ValueError, base64.a85decode, b'abcdey', adobe=False) self.assertRaises(ValueError, base64.a85decode, b'a b\nc', adobe= False, ignorechars=b'') self.assertRaises(ValueError, base64.a85decode, b's', adobe=False) self.assertRaises(ValueError, base64.a85decode, b's8', adobe=False) self.assertRaises(ValueError, base64.a85decode, b's8W', adobe=False) self.assertRaises(ValueError, base64.a85decode, b's8W-', adobe=False) self.assertRaises(ValueError, base64.a85decode, b's8W-"', adobe=False)
def test_a85decode_errors(self): illegal = (set(range(32)) | set(range(118, 256))) - set(b' \t\n\r\v') for c in illegal: with self.assertRaises(ValueError, msg=bytes([c])): base64.a85decode(b'!!!!' + bytes([c])) with self.assertRaises(ValueError, msg=bytes([c])): base64.a85decode(b'!!!!' + bytes([c]), adobe=False) with self.assertRaises(ValueError, msg=bytes([c])): base64.a85decode(b'<~!!!!' + bytes([c]) + b'~>', adobe=True) self.assertRaises(ValueError, base64.a85decode, b"malformed", adobe=True) self.assertRaises(ValueError, base64.a85decode, b"<~still malformed", adobe=True) # With adobe=False (the default), Adobe framing markers are disallowed self.assertRaises(ValueError, base64.a85decode, b"<~~>") self.assertRaises(ValueError, base64.a85decode, b"<~~>", adobe=False) base64.a85decode(b"<~~>", adobe=True) # sanity check self.assertRaises(ValueError, base64.a85decode, b"abcx", adobe=False) self.assertRaises(ValueError, base64.a85decode, b"abcdey", adobe=False) self.assertRaises(ValueError, base64.a85decode, b"a b\nc", adobe=False, ignorechars=b"") self.assertRaises(ValueError, base64.a85decode, b's', adobe=False) self.assertRaises(ValueError, base64.a85decode, b's8', adobe=False) self.assertRaises(ValueError, base64.a85decode, b's8W', adobe=False) self.assertRaises(ValueError, base64.a85decode, b's8W-', adobe=False) self.assertRaises(ValueError, base64.a85decode, b's8W-"', adobe=False)
def test_a85_padding(self): eq = self.assertEqual eq(base64.a85encode(b"x", pad=True), b'GQ7^D') eq(base64.a85encode(b"xx", pad=True), b"G^'2g") eq(base64.a85encode(b"xxx", pad=True), b'G^+H5') eq(base64.a85encode(b"xxxx", pad=True), b'G^+IX') eq(base64.a85encode(b"xxxxx", pad=True), b'G^+IXGQ7^D') eq(base64.a85decode(b'GQ7^D'), b"x\x00\x00\x00") eq(base64.a85decode(b"G^'2g"), b"xx\x00\x00") eq(base64.a85decode(b'G^+H5'), b"xxx\x00") eq(base64.a85decode(b'G^+IX'), b"xxxx") eq(base64.a85decode(b'G^+IXGQ7^D'), b"xxxxx\x00\x00\x00")
def decode(payload: Union[bytes, str]) -> bytes: print("Decoding Layer 5...") result: bytes = b'' decoded = base64.a85decode(payload, adobe=True) # As per instruction: # First 32 bytes: The 256-bit key encrypting key (KEK). key_encryption_key = decoded[0:32] # Next 8 bytes: The 64-bit initialization vector (IV) for # the wrapped key. wrapped_key_init_vector = decoded[32:40] # Next 40 bytes: The wrapped (encrypted) key. When # decrypted, this will become the 256-bit encryption key. wrapped_key = decoded[40:80] # Next 16 bytes: The 128-bit initialization vector (IV) for # the encrypted payload. init_vector = decoded[80:96] # All remaining bytes: The encrypted payload. encrypted = decoded[96:] # The first step is to use the KEK and the 64-bit IV to unwrap the wrapped key. key = aes_key_unwrap(wrapped_key, key_encryption_key, wrapped_key_init_vector) # print("key:", key) # The second step is to use the unwrapped key and the 128-bit IV to decrypt the rest of the payload. cipher = AES.new(key, AES.MODE_CTR, nonce=b'', initial_value=init_vector) result = cipher.decrypt(pad(encrypted, AES.block_size)) with open("layer6", "wb+") as layer_file: layer_file.write(result) return result
def func(self): try: index = 0 _code_a = '' _code_b = '' _de_a = '' _de_b = '' while index < len(self.text): _code_a += self.text[index] index += 2 index = 1 while index < len(self.text): _code_b += self.text[index] index += 2 try: _de_a += base64.a85decode(str.encode(_code_a)).decode('utf-8') _de_b += base64.b85decode(str.encode(_code_b)).decode('utf-8') except Exception as exc: print(exc) self.result['message'] = 'Строка повреждена' return True if _de_a == _de_b and _de_a != '': self.result['message'] = _de_a return True except Exception as e: self.result['message'] = str(e) return False
def bguess(encoded): try: print("[+] base91 : ->", base91.decode(encoded), "\n") except: print("[-] base91 : -> Invalid\n") try: print("[+] base85 : ->", base64.b85decode(encoded), "\n") except: print("[-] base85 : -> Invalid\n") try: print("[+] ASCII85 : -> ", base64.a85decode(encoded), "\n") except: print("[-] ASCII85 : -> Invalid\n") try: print("[+] base64 : ->", base64.b64decode(encoded), "\n") except: print("[-] base64 : -> Invalid\n") try: print("[+] base62 : ->", base62.decode(encoded), "\n") except: print("[-] base62 : -> Invalid\n") try: print("[+] base58 : ->", base58.b58decode(encoded), "\n") except: print("[-] base58 : -> \n") try: print("[+] base32 : ->", base64.b32decode(encoded), "\n") except: print("[-] base32 : -> Invalid\n") try: print("[+] base16 : ->", base64.b16decode(encoded), "\n") except: print("[-] base16 : -> Invalid\n")
def layer5(payload): decoded = base64.a85decode(payload, adobe=True) key = aes_unwrap_key(decoded[:32], decoded[40:80], int.from_bytes(decoded[32:40], byteorder='big')) cipher = AES.new(key, AES.MODE_CBC, iv=decoded[80:96]) data = cipher.decrypt(decoded[96:]) return data.decode()
def main(): inp = input('->') encoded = inp.encode( 'utf-8') # encoded the input (we need a bytes like object) a85encoded = base64.a85encode(encoded) # a85encoded the encoded string print(a85encoded) print(base64.a85decode(a85encoded).decode('utf-8')) # decoded it
def _sync(self): imap = self._chump.get_imap() typ, count = imap.select() count = count[0].decode() if count == '0': return typ, data = imap.fetch('1:*', '(UID RFC822)') messages = [ x for x in data if isinstance(x, tuple) ] offers = [] for (mkey, mvalue) in messages: message = email.message_from_string(mvalue.decode()) uid = re.search(rb'UID\s*(\d+)', mkey).group(1).decode() full_message = None try: # https://stackoverflow.com/questions/45124127/ full_message = msgpack.unpackb(base64.a85decode(message.get_payload()), encoding='utf-8') except: # Just ignore seriously malformed messages pass if full_message is not None and 'key' in full_message: if full_message['key'] == '__answer': self._chump.tcpdict[full_message['sender']].got_answer(full_message['body']) self.doomed.put(uid) elif full_message['key'] == '__offer': self.doomed.put(uid) if (int(time()) - full_message['timestamp']) < 60: self._chump.tcpdict[full_message['sender']].got_offer(full_message['offer']) else: self._chump.queues[full_message['key']][uid] = full_message else: self.doomed.put(uid)
async def decode_ascii85(self, ctx, *, input: str): """ Decode ASCII85 """ try: await self.encryptout(ctx, "ASCII85 -> Text", base64.a85decode(input.encode('UTF-8'))) except Exception: await ctx.send("Invalid ASCII85...")
def main() -> None: inp = input("->") encoded = inp.encode( "utf-8") # encoded the input (we need a bytes like object) a85encoded = base64.a85encode(encoded) # a85encoded the encoded string print(a85encoded) print(base64.a85decode(a85encoded).decode("utf-8")) # decoded it
def four(): txt = open("./data/payload_4.txt", "r") txt_string = txt.read() txt_decode = base64.a85decode(txt_string, adobe=True) decoded = [] start = 0 while start < len(txt_decode): (size, source_ip, dest_ip, ipv4_valid) = ipv4_header( txt_decode[start : start + 20] ) (dest_port, udp_valid) = udp_header( txt_decode[start + 20 : start + 28], txt_decode[start : start + 20], txt_decode[start + 28 : start + size], ) if ( source_ip == "10.1.1.10" and dest_ip == "10.1.1.200" and dest_port == 42069 and ipv4_valid and udp_valid ): decoded.extend(txt_decode[start + 28 : start + size]) start = start + size five = open("./decrypted/5.txt", "w") five.write(bytes(decoded).decode("utf8")) five.close()
def decrypt85(value85): try: decode85 = base64.a85decode(value85) dec85 = decode85.decode("UTF-8") print("Decoded with Base85: " + dec85) except: print("Value is not Base85.")
def decode(payload: Union[bytes, str]) -> bytes: print("Decoding Layer 2...") result: bytes = b'' data_group: str = '' i = 0 for byte in base64.a85decode(payload, adobe=True): # print("---") # print("byte:",byte) first_seven_bits = format(byte, '08b')[:7] # print("first_seven_bits:",first_seven_bits) parity_bit = byte & 0b00000001 # print("parity_bit:",parity_bit) num_one_bits = first_seven_bits.count('1') # print("num_one_bits:",num_one_bits) if (num_one_bits % 2) == parity_bit: data_group += first_seven_bits i += 1 # print("i:", i) if i % 8 == 0: # print(data_group) for j in range(7): # print("j:", j) data_byte = int(data_group[j * 8:(j + 1) * 8], 2) # print("data_group[j*8:(j+1)*8]:",data_group[j*8:(j+1)*8]) result += data_byte.to_bytes(1, 'big') data_group = str() with open("layer3", "wb+") as layer_file: layer_file.write(result) return result
def decrypt(arguments): """Decrypt the input file""" if arguments.input_file: source_data = arguments.input_file.read_bytes() else: source_data = sys.stdin.buffer.read() # try: source_data = base64.a85decode(source_data) except ValueError: pass # decryption_password = getpass.getpass( 'Enter decryption password: '******'utf-8') scrypt_file = pyscrypt.ScryptFile(io.BytesIO(source_data), password=decryption_password) try: decrypted_data = scrypt_file.read() except pyscrypt.file.InvalidScryptFileFormat as error: logging.error('Error while decrypting input: %s', error) return False # decompressed_data = lzma.decompress(XZ_HEADER + decrypted_data) if arguments.output_file: arguments.output_file.write_bytes(decompressed_data) else: sys.stdout.buffer.write(decompressed_data) # return True
def ascii2uuid(s: str) -> str: """ Convert an ASCII string to an UUID hexadecimal string :param s: an ASCII string :return: an UUID hexadecimal string """ return str(uuid.UUID(bytes=base64.a85decode(s)))
def parse_packet(self, packet: bytes): data = None try: id, command, data = packet.split(b':', 2) except ValueError: try: id, command = packet.split(b':') except ValueError: return None id = int(id) retval = None try: if command == b'fullscreen': pygame.display.toggle_fullscreen() elif command == b'setframerate': self.framerate = int(data) elif command == b'resize': x, y = data.split(b'x') x = int(x) y = int(y) self.display = pygame.display.set_mode((x, y)) elif command == b'img': x, y, encoding, compression, imagestr = data.split(b':', 4) x = int(x) y = int(y) encoding = encoding.decode() compression = compression.decode() if compression == 'gzip': imagestr = gzip.decompress(imagestr) elif compression == 'base64': imagestr = base64.b64decode(imagestr) elif compression == 'base32': imagestr = base64.b32decode(imagestr) elif compression == 'base85': imagestr = base64.a85decode(imagestr) elif compression == 'base16': imagestr = base64.b16decode(imagestr) elif compression == 'none': pass else: raise ValueError( 'compression method `{}` not supported'.format( compression)) self.surface = pygame.image.fromstring(imagestr, (x, y), encoding) elif command == b'exec': code = data.decode() exec(code) elif command == b'eval': code = data.decode() retval = eval(code) elif command == b'ping': pass else: raise ValueError('command {} not supported'.format(command)) self.ack(id, retval) except: exc = traceback.format_exc().split('\n')[-2] self.nak(id, exc)
async def decode_ascii85(self, ctx, *, input: commands.clean_content = None): if not input: input = await self.detect_file(ctx) try: await self.encryptout(ctx, "ASCII85 -> Text", base64.a85decode(input.encode('UTF-8'))) except Exception: await ctx.send("Invalid ASCII85...")
def _convert_payloads(raw_payloads): payloads = [] for item in raw_payloads: try: payloads.append(a85decode(item, adobe=True)) except Exception as e: logging.error('Could not decode payload: {} - {}'.format(sys.exc_info()[0].__name__, e)) return payloads
def six(): txt = open("./data/payload_6.txt", "r") txt_string = txt.read() txt_decode = base64.a85decode(txt_string, adobe=True) # vm = Vm(bytes.fromhex('50 48 c2 02 a8 4d 00 00 00 4f 02 50 09 c4 02 02 e1 01 4f 02 c1 22 1d 00 00 00 48 30 02 58 03 4f 02 b0 29 00 00 00 48 31 02 50 0c c3 02 aa 57 48 02 c1 21 3a 00 00 00 48 32 02 48 77 02 48 6f 02 48 72 02 48 6c 02 48 64 02 48 21 02 01 65 6f 33 34 2c')) vm = Vm(bytearray(txt_decode)) vm.run()
def _convert_payloads(raw_payloads): payloads = [] for item in raw_payloads: try: payloads.append(a85decode(item, adobe=True)) except binascii.Error as error_message: logging.error('Could not decode payload: {}'.format(error_message)) return payloads
def test_decode(self): for phrase in self.phrases_to_decode: phrase = phrase.encode("utf-8") actual = ascii85.decode(phrase) expected = base64.a85decode(phrase, adobe=True) self.assertEqual(actual, expected)
def step_decode(text_string: str): encoded_bytes = bytes(text_string, encoding="ascii") logging.debug(f"Sanity : {encoded_bytes}") decoded_bytes_array = [_steps_down(byte) for byte in encoded_bytes] decoded_bytes = bytes(decoded_bytes_array) logging.debug(f"Decoded + unshifted : {decoded_bytes}") text_bytes = a85decode(decoded_bytes) return str(text_bytes, encoding="ascii")
def start(): txt = open("./data/payload.txt", "r") txt_string = txt.read() txt_decode = base64.a85decode(txt_string, adobe=True) one = open("./decrypted/1.txt", "w") one.write(txt_decode.decode("UTF-8")) one.close()
async def decode_ascii85(self, ctx, *, _input: clean_content = None): """ Decode in ASCII85 """ if not _input: _input = await detect_file(ctx) try: await encrypt_out(ctx, "ASCII85 -> Text", base64.a85decode(_input.encode('UTF-8'))) except Exception: await ctx.send("Invalid ASCII85...")
def b85(text, encode=False): import base64 text = bytes(text, "utf-8") if encode: return SUCCESS % base64.a85encode(text).decode("utf-8") try: return SUCCESS % str(base64.a85decode(text))[2:-1] except: return FAIL % "Invalid base85 input"
def test_a85decode(self): eq = self.assertEqual tests = { b'': b'', b'GB\\6`E-ZP=Df.1GEb>': b'www.python.org', b"""! ! * -'"\n\t\t9eu\r\n7# RL\vhG$k3[W&.oNg'GVB"(`=52*$$""" b"""(B+<_pR,UFcb-n-Vr/1iJ-0JP==1c70M3&s#]4?Ykm5X@_(6q'R884cE""" b"""H9MJ8X:f1+h<)lt#=BSg3>[:ZC?t!MSA7]@cBPD3sCi+'.E,fo>FEMbN""" b"""G^4U^I!pHnJ:W<)KS>/9Ll%"IN/`jYOHG]iPa.Q$R$jD4S=Q7DTV8*TU""" b"""nsrdW2ZetXKAY/Yd(L?['d?O\\@K2_]Y2%o^qmn*`5Ta:aN;TJbg"GZd""" b"""*^:jeCE.%f\\,!5gtgiEi8N\\UjQ5OekiqBum-X60nF?)@o_%qPq"ad`""" b"""r;HT""": bytes(range(255)), b"""@:E_WAS,RgBkhF"D/O92EH6,BF`qtRH$VbC6UX@47n?3D92&&T:Jand;c""" b"""Hat='/U/0JP==1c70M3&r-I,;<FN.OZ`-3]oSW/g+A(H[P""": b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234' b'56789!@#0^&*();:<>,. []{}', b'DJpY:@:Wn_DJ(RS': b'no padding..', b'H=_,8+Cf>,E,oN2F(oQ1z': b'zero compression\x00\x00\x00\x00', b'H=_,8+Cf>,E,oN2F(oQ1!!!!': b'zero compression\x00\x00\x00', b'6>q!aA79M(3WK-[!!': b"Boundary:\x00\x00\x00\x00", b';fH/TAKYK$D/aMV+<VdL': b'Space compr: ', b'rr': b'\xff', b's8N': b'\xff'*2, b's8W*': b'\xff'*3, b's8W-!': b'\xff'*4, } for data, res in tests.items(): eq(base64.a85decode(data), res, data) eq(base64.a85decode(data, adobe=False), res, data) eq(base64.a85decode(data.decode("ascii"), adobe=False), res, data) eq(base64.a85decode(b'<~' + data + b'~>', adobe=True), res, data) eq(base64.a85decode(data + b'~>', adobe=True), res, data) eq(base64.a85decode('<~%s~>' % data.decode("ascii"), adobe=True), res, data) eq(base64.a85decode(b'yy', foldspaces=True, adobe=False), b' '*8) eq(base64.a85decode(b'y+<Vd', foldspaces=True, adobe=False), b' '*7) eq(base64.a85decode(b'y+<U', foldspaces=True, adobe=False), b' '*6) eq(base64.a85decode(b'y+9', foldspaces=True, adobe=False), b' '*5) self.check_other_types(base64.a85decode, b'GB\\6`E-ZP=Df.1GEb>', b"www.python.org")
def read_from_source(self, n): out_data = b'' while len(out_data) < n: in_data = self._source.read(n) in_data = self.rest + in_data.translate(None, ASCII_WHITESPACE) if not in_data: self.rest = b'' break eod_index = in_data.find(b'~') if eod_index > 0: assert in_data[eod_index:] == b'~>' out_data += a85decode(in_data[:eod_index]) self.rest = b'' break rest_len = len(in_data) % 5 if rest_len: input, self.rest = in_data[:-rest_len], in_data[-rest_len:] else: input, self.rest = in_data, b'' out_data += a85decode(input) return out_data
def read_game_data(username): filename = "savefile_" + username + ".txt" with open(filename, "rb") as f: data = f.read() data = data[:data.rindex(b';')] utf8_decoded_data = a85decode(data).decode("utf-8") print('utf8_decoded_data:', utf8_decoded_data) return game_model.GameState(utf8_decoded_data.split("_"))
def decodebase(encoder): #Functions for decode for all base's decode = {} try: decode["Base64"] = str(base64.b64decode(encoder), "utf-8") except: decode["Base64"] = "Not is Base64" try: decode["Base32"] = str(base64.b32decode(encoder), "utf-8") except: decode["Base31"] = "Not is Base32" try: decode["Base16"] = str(base64.b16decode(encoder), "utf-8") except: decode["Base16"] = "Not is Base16" try: decode["a85"] = str(base64.a85decode(encoder), "utf-8") except: decode["a85"] = "Not is a85" return decode
def a85encode(data, **kwargs): return base64.a85decode(data)
def _handle_client(self, client_reader, client_writer, address): """ This method actually does the work to handle the requests for a specific client. The protocol is byte AND line oriented, the command is read first (8 bytes) and matched against available commands, the complete line (up to 64k) is read into memory and must end with newline character. The received data is verified against the received user id's public key. Once verified, the matched command is executed. @param client_reader: StreamReader object @param client_writer: StreamWriter object """ while True: # recevied incoming data time stamp stamp = int(time()) # read command first, only take first 8 bytes cmd = yield from client_reader.readexactly(COMMAND_LENGTH) if not cmd: # nothing received from client break ################ # Data checking ################ # check received command is valid try: command = Commands[int(cmd)] except ValueError: logging.info("\t".join(("Invalid Command Provided By Client", "IP: {!r}".format(address), "Command: {!r}".format(cmd)))) yield from self._close_connection(client_writer, INVALID_COMMAND) return try: # use of encoded data allows for direct readline() data = yield from client_reader.readline() except asyncio.futures.TimeoutError: yield from self._close_connection(client_writer, TIMEOUT) return # clear up data before proceeding (i.e newline char) data = data.strip() ################ # Authorisation ################ if command != friendAcceptance: try: data = a85decode(data, foldspaces=True) except ValueError: logging.info("Invalid data received, unable to decode as ASCII85") yield from self._close_connection(client_writer, INVALID_COMMAND) return # verify data integrity try: # using getAuthority hits the disk db data = VerifyKey(getAuthority(self.safe, self.profileId, self.friendMasks[data[-36:]])[0], encoder=HexEncoder).verify(data) except (BadSignatureError, TypeError): # signed data does not match stored public key for provided user id logging.warning('\t'.join(("Unable to verify sent data", "IP: {!r}".format(address), "Data: {!r}".format(data), "Sent ID: {!r}".format(data[-36:])))) yield from self._close_connection(client_writer, INVALID_DATA) return # data received as: timestamp, hash chain hex, destination user id, data, sender user id tstamp, chain, dest, origin = data[:10], data[10:50], data[50:86], data[-36:] data = data[86:-36] ########################### # Message integrity checks ########################### integrity = True # validation checks if dest != self.uid: logging.warning("Message Integrity Failure: User id destination {!r} differs from logged in user".format(dest)) integrity = False try: if integrity and (stamp + LIMIT_MESSAGE_TIME) < int(tstamp) < (stamp - LIMIT_MESSAGE_TIME): logging.warning("Message Integrity Failure: Message is either too old or in the future, current time '{}' received stamp '{}'".format(stamp, int(tstamp))) integrity = False except ValueError: logging.warning("Message Integrity Failure: Message time {!r} is invalid".format(tstamp)) if integrity and isValidUUID(origin): hchain = bytes(sha1(b''.join((self.hashchain[address], data))).hexdigest(), encoding='ascii') if hchain != chain: logging.warning("Message Integrity Failure: Provided hash chain {!r} does not match local {!r}".format(chain, hchain)) integrity = False else: logging.warning("Message Integrity Failure: Invalid UUID provided by {!r}".format(origin)) integrity = False if not integrity: yield from self._close_connection(client_writer, INVALID_COMMAND) return try: # ensure command integrity for authorised commands assert Commands[int(data[-COMMAND_LENGTH:])] == command except (ValueError, AssertionError): logging.info('\t'.join(("Client unsigned CMD data does not equal signed CMD", "IP: {!r}".format(address), "Unsigned Command: {!r}".format(cmd), "Signed Command: {!r}".format(data[-COMMAND_LENGTH:])))) yield from self._close_connection(client_writer, INVALID_DATA) return # all checks cleared, update hash chain self.hashchain[address] = hchain # data verified, execute command with data and origin user id returnData = yield from self._command_dispatch(client_reader, client_writer, command, b''.join((data, origin))) else: returnData, authToken = yield from friendAcceptance(client_reader, client_writer, self.safe, self.profileId, data) if authToken is not None: self.auth.append(authToken) # send command result to client client_writer.write(returnData) # Flush buffer yield from client_writer.drain()
#!/usr/bin/env python3 import base64 import codecs text = "HR7DYQ3ON4TC6U2AFAZDGJK3J44TYXZUNRCTATK2GEZDGJR5JJUC6ULUFQZEI5L6HY======" print("\t" + text) text = base64.b32decode(text) print("B32:\t" + str(text)[2:-1]) text = base64.a85decode(text, adobe=True) print("A85:\t" + str(text)[2:-1]) text = codecs.encode(str(text), "rot-13") print("R13:\t" + str(text)[2:-1])
def parse_str(self, encode_str, decode_method, m_list): if len(m_list) > self.max_depth: return False, encode_str # encode_str = deepcopy(encode_str) encode_str = utf8(encode_str) if decode_method in ['zlib']: encode_str = utf8(encode_str) else: encode_str = to_unicode(encode_str) raw_encode_str = deepcopy(encode_str) if len(encode_str) <= 0: return False, raw_encode_str try: if decode_method == 'base16': # 避免无限递归 # base_list = ('base16', 'base32', 'base64', 'urlsafe_b64') # base_list = () if len(encode_str) < 4: return False, raw_encode_str encode_str = encode_str.upper() rex = re.compile('^[0-9A-F]+[=]*$', re.MULTILINE) if self.regex_match(rex, encode_str): decode_str = partial_base16_decode(encode_str) else: return False, raw_encode_str elif decode_method == 'base32': encode_str = encode_str.strip().replace(' ', '').replace('\n', '') # 避免无限递归 # base_list = ('base16', 'base32', 'base64', 'urlsafe_b64') # base_list = () if len(encode_str) < 4: return False, raw_encode_str encode_str = encode_str.upper() rex = re.compile('^[A-Z2-7=]+$', re.MULTILINE) # 自动纠正填充 if self.regex_match(rex, encode_str): decode_str = partial_base32_decode(encode_str) else: return False, raw_encode_str elif decode_method == 'base64': encode_str = encode_str.strip().replace(' ', '').replace('\n', '') # 避免无限递归 # base_list = ('base16', 'base32', 'base64', 'urlsafe_b64') # base_list = () if len(encode_str) < 4: return False, raw_encode_str rex = re.compile('^[A-Za-z0-9+/=]+$', re.MULTILINE) # 自动纠正填充 if self.regex_match(rex, encode_str): decode_str = partial_base64_decode(encode_str) else: return False, raw_encode_str elif decode_method == 'urlsafe_b64': encode_str = encode_str.strip().replace(' ', '').replace('\n', '') # base_list = ('base16', 'base32', 'base64', 'urlsafe_b64') # base_list = () if len(encode_str) < 4: return False, raw_encode_str rex = re.compile('^[A-Za-z0-9-_=]+$', re.MULTILINE) # 自动纠正填充 if self.regex_match(rex, encode_str): decode_str = urlsafe_b64decode(base_padding(encode_str, 4)) else: return False, raw_encode_str elif decode_method == 'ascii_85': if len(encode_str) < 7: return False, raw_encode_str if PY2: return False, raw_encode_str rex = re.compile('^[A-Za-z0-9!#$%&()*+\-;<=>?@^_`{|}~]+$', re.MULTILINE) if self.regex_match(rex, encode_str): decode_str = a85decode(utf8(encode_str)) else: return False, encode_str elif decode_method == 'base85': if len(encode_str) < 7: return False, raw_encode_str if PY2: return False, raw_encode_str rex = re.compile('^[A-Za-z0-9!#$%&()*+\-;<=>?@^_`{|}~]+$', re.MULTILINE) if self.regex_match(rex, encode_str): decode_str = b85decode(utf8(encode_str)) else: return False, encode_str elif decode_method == 'pawn_shop': try: encode_str = encode_str.decode('gb2312') except: pass encode_str = to_unicode(encode_str) encode_str = encode_str.replace(' ', '').strip() code_base = '口由中人工大王夫井羊' decode_str = [] for t in encode_str: if t in code_base: i = code_base.index(t) decode_str.append(str(i)) else: return False, raw_encode_str decode_str = ''.join(decode_str) if len(decode_str) < 0: return False, raw_encode_str elif decode_method == 'decimal': if len(encode_str) < 4: return False, raw_encode_str rex = re.compile('^[0-9]+$', re.MULTILINE) if not self.regex_match(rex, encode_str): return False, raw_encode_str # 解码后是 0xab1234,需要去掉前面的 0x decode_str = hex(int(encode_str))[2:].rstrip('L') elif decode_method == 'binary': rex = re.compile('^[0-1]+$', re.MULTILINE) if not self.regex_match(rex, encode_str): return False, raw_encode_str # 不足8个的,在后面填充0 padding_length = (8 - len(encode_str) % 8) % 8 encode_str = '%s%s' % (encode_str, '0' * padding_length) # 解码后是 0xab1234,需要去掉前面的 0x decode_str = hex(int(encode_str, 2))[2:].rstrip('L') elif decode_method in ['octal', 'octal_ascii', 'octal_binary']: # 8进制转成16进制的数据 rex = re.compile('^[0-7]+$', re.MULTILINE) if not self.regex_match(rex, encode_str): return False, raw_encode_str rex = re.compile('^[0-1]+$', re.MULTILINE) if self.regex_match(rex, encode_str): return False, raw_encode_str if len(encode_str) < 4: return False, raw_encode_str if decode_method == 'octal': # 解码后是 0xab1234,需要去掉前面的 0x decode_str = hex(int(encode_str, 8))[2:].rstrip('L') elif decode_method == 'octal_ascii': encode_str = encode_str.replace(' ', '').strip() # 8 进制的 177 转成十进制后是 128 tmp_list = list(encode_str) ascii_list = [] while len(tmp_list) > 0: tmp_str = ''.join(tmp_list[:3]) if int(tmp_str, 8) > 127: tmp_str = ''.join(tmp_list[:2]) tmp_list = tmp_list[2:] else: tmp_list = tmp_list[3:] ascii_list.append(chr(int(tmp_str, 8))) decode_str = ''.join(ascii_list) elif decode_method == 'octal_binary': # 因为这里有补0的操作,要避免无限递归 if len(m_list) > 0 and \ (m_list[-1] in ('octal_binary', 'octal', 'binary') or len(encode_str) < 8): return False, raw_encode_str # 将8进制直接转成16进制,也就是3个8进制数字转成2个16进制字符 # 先将每个8进制数字转成二进制,不足3个的前面补0 encode_str = encode_str.replace(' ', '').strip() tmp_bin_list = ['%03d' % int(bin(int(t))[2:]) for t in list(encode_str)] tmp_bin_list = [t for t in tmp_bin_list] # logger.info(tmp_bin_list) decode_str = ''.join(tmp_bin_list) else: return False, raw_encode_str elif decode_method == 'decimal_ascii': if len(encode_str) < 4: return False, raw_encode_str encode_str = encode_str.replace(' ', '').strip() rex = re.compile('^[0-9]+$', re.MULTILINE) if not self.regex_match(rex, encode_str): return False, raw_encode_str # ascii 字符串,10进制最大127 tmp_list = list(encode_str) ascii_list = [] while len(tmp_list) > 0: tmp_str = ''.join(tmp_list[:3]) if int(tmp_str) > 127: tmp_str = ''.join(tmp_list[:2]) tmp_list = tmp_list[2:] else: tmp_list = tmp_list[3:] ascii_list.append(chr(int(tmp_str))) decode_str = ''.join(ascii_list) elif decode_method in ['switch_case', 'reverse_alphabet', 'reverse']: # 如果这里不做限制,会无限递归下去 if len(m_list) > 0 and m_list[-1] in ['switch_case', 'reverse_alphabet', 'reverse']: return False, raw_encode_str # 一定要包含 ascii 字符 tmp_data = [t for t in encode_str if t in string.ascii_letters] if len(tmp_data) <= 0: return False, raw_encode_str # rex = re.compile('^[A-Za-z0-9+/=]$', re.MULTILINE) # if not self.regex_match(rex, encode_str): # return False, raw_encode_str if decode_method == 'switch_case': new_data = [] for t in encode_str: if t in string.ascii_lowercase: t = t.upper() elif t in string.ascii_uppercase: t = t.lower() new_data.append(t) decode_str = ''.join(new_data) elif decode_method == 'reverse_alphabet': # 字母逆序,a->z, z->a new_data = [] for t in encode_str: if t in string.ascii_letters: if t in string.ascii_lowercase: t = ord(t) + (25 - (ord(t) - ord('a')) * 2) t = chr(t) else: t = ord(t) + (25 - (ord(t) - ord('A')) * 2) t = chr(t) new_data.append(t) decode_str = ''.join(new_data) elif decode_method == 'reverse': # 逆序 decode_str = encode_str[::-1] else: return False, raw_encode_str elif decode_method == 'urlencode': if len(encode_str) < 4: return False, raw_encode_str decode_str = unquote_plus(encode_str) elif decode_method == 'hex': if len(encode_str) < 4: return False, raw_encode_str encode_str = encode_str.lower() rex = re.compile('^[a-f0-9]+$', re.MULTILINE) if self.regex_match(rex, encode_str.lower()): # 修正基数位数的16进制数据 if len(encode_str) % 2 != 0: encode_str += '0' decode_str = hex2str(encode_str) else: return False, raw_encode_str elif decode_method == 'zlib': if len(encode_str) < 4: return False, raw_encode_str try: decode_str = zlib.decompress(utf8(encode_str)) except: return False, raw_encode_str else: decode_str = encode_str.decode(decode_method) if len(decode_str) <= 0: return False, raw_encode_str elif utf8(encode_str) == utf8(decode_str): return False, raw_encode_str else: # 解码的内容只有可打印字符,才认为合法 if self.only_printable: decode_str = to_unicode(decode_str) if isinstance(decode_str, bytes): return False, raw_encode_str tmp_decode_str = list(decode_str) printable_count = 0 for t in tmp_decode_str: if str(t) in string.printable: printable_count += 1 # 如果可打印字符低于一定的百分比,就认为解码失败 if printable_count * 1.0 / len(tmp_decode_str) < self.printable_percent: return False, raw_encode_str return True, decode_str except Exception as e: if self.verbose: logger.exception(e) return False, raw_encode_str
## Py-supergolf.py import sys, base64, codecs with open(sys.argv[1]) as data_stream: exec( base64.a85decode( codecs.decode( codecs.decode( ''.join(data_stream.readlines()), 'zip' ), 'bz2' ) ) ) )
def main(): inp = input('->') encoded = inp.encode('utf-8') #encoded the input (we need a bytes like object) a85encoded = base64.a85encode(encoded) #a85encoded the encoded string print(a85encoded) print(base64.a85decode(a85encoded).decode('utf-8'))#decoded it