| 1 | + | #!/usr/bin/env python3 |
| 2 | + | |
| 3 | + | from typing import Iterator |
| 4 | + | from base64 import b64encode |
| 5 | + | |
| 6 | + | |
| 7 | + | # Stolen from: https://gist.github.com/hsauers5/491f9dde975f1eaa97103427eda50071 |
| 8 | + | def key_scheduling(key: bytes) -> list: |
| 9 | + | sched = [i for i in range(0, 256)] |
| 10 | + | |
| 11 | + | i = 0 |
| 12 | + | for j in range(0, 256): |
| 13 | + | i = (i + sched[j] + key[j % len(key)]) % 256 |
| 14 | + | tmp = sched[j] |
| 15 | + | sched[j] = sched[i] |
| 16 | + | sched[i] = tmp |
| 17 | + | |
| 18 | + | return sched |
| 19 | + | |
| 20 | + | |
| 21 | + | def stream_generation(sched: list[int]) -> Iterator[bytes]: |
| 22 | + | i, j = 0, 0 |
| 23 | + | while True: |
| 24 | + | i = (1 + i) % 256 |
| 25 | + | j = (sched[i] + j) % 256 |
| 26 | + | tmp = sched[j] |
| 27 | + | sched[j] = sched[i] |
| 28 | + | sched[i] = tmp |
| 29 | + | yield sched[(sched[i] + sched[j]) % 256] |
| 30 | + | |
| 31 | + | |
| 32 | + | def encrypt(plaintext: bytes, key: bytes) -> bytes: |
| 33 | + | sched = key_scheduling(key) |
| 34 | + | key_stream = stream_generation(sched) |
| 35 | + | |
| 36 | + | ciphertext = b'' |
| 37 | + | for char in plaintext: |
| 38 | + | enc = char ^ next(key_stream) |
| 39 | + | ciphertext += bytes([enc]) |
| 40 | + | |
| 41 | + | return ciphertext |
| 42 | + | |
| 43 | + | |
| 44 | + | if __name__ == '__main__': |
| 45 | + | # msfvenom -p windows/x64/exec CMD=calc.exe -f raw -o calc.bin |
| 46 | + | with open('calc.bin', 'rb') as f: |
| 47 | + | result = encrypt(plaintext=f.read(), key=b'aaaaaaaaaaaaaaaa') |
| 48 | + | |
| 49 | + | print(b64encode(result).decode()) |