Skip to content

Instantly share code, notes, and snippets.

@Joshix-1
Last active April 19, 2024 21:22
Show Gist options
  • Select an option

  • Save Joshix-1/9e1c3481562a2873a94d12c1548dcc67 to your computer and use it in GitHub Desktop.

Select an option

Save Joshix-1/9e1c3481562a2873a94d12c1548dcc67 to your computer and use it in GitHub Desktop.
from __future__ import annotations
import base64
import lzma
import marshal
import sys
import types
from collections.abc import Callable
from functools import partial
from pathlib import Path
from typing import NewType
PythonCode = NewType("PythonCode", bytes)
def compress_bytes(data: bytes) -> PythonCode:
"""Compress bytes to python code."""
COMPRESSIONS: list[tuple[Callable[[bytes], bytes], bytes]] = [
(__import__("bz2").compress, b"__import__('bz2').decompress"),
(__import__("gzip").compress, b"__import__('gzip').decompress"),
(__import__("lzma").compress, b"__import__('lzma').decompress"),
(partial(lzma.compress, preset=9 | lzma.PRESET_EXTREME), b"__import__('lzma').decompress"),
]
min_code = PythonCode(repr(data).encode())
min_length = len(min_code)
for compress, decompress in COMPRESSIONS:
result = decompress + b"(__import__('base64').b85decode('" + base64.b85encode(compress(data)) + b"'))"
if len(result) < min_length:
min_length = len(result)
min_code = PythonCode(result)
return min_code
def compress_code(code: bytes, filename = "__main__") -> PythonCode:
"""Compress python code to python code."""
min_code = PythonCode(code)
min_length = len(min_code)
compiled: types.CodeType = compile(
code,
filename,
"exec",
flags=annotations.compiler_flag,
dont_inherit=True,
optimize=2
).replace(co_linetable=b"")
def m_dumps(o: types.CodeType, version: int) -> bytes:
return marshal.dumps(o, version)
CONVERTS: list[tuple[Callable[[types.CodeType], bytes], bytes, int]] = [
(marshal.dumps, b"__import__('marshal').loads"),
*(
(partial(m_dumps, version=v), b"__import__('marshal').loads")
for v in range(marshal.version)
),
]
for convert, deconvert in CONVERTS:
result = b"exec(" + deconvert + b"(" + compress_bytes(convert(compiled)) + b"))"
if len(result) < min_length or min_code == code:
min_length = len(result)
min_code = PythonCode(result)
return min_code
if __name__ == "__main__":
path = Path(__file__)
sys.stdout.buffer.write(
compress_code(path.read_bytes(), path.name)
)
sys.stdout.buffer.write(b"\n")
sys.stdout.buffer.flush()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment