| 6 | |
| 7 | |
| 8 | class XorCipher: |
| 9 | __slots__ = ("key", "_key_length", "_fname", "_ciphertext", "_plaintext") |
| 10 | |
| 11 | def __init__(self, filename: str, xor_key: str) -> None: |
| 12 | self.key = str(xor_key) |
| 13 | self._key_length = len(self.key) |
| 14 | self._fname = filename |
| 15 | self._ciphertext = "" |
| 16 | self._plaintext = b"" |
| 17 | |
| 18 | def _xor_crypt(self) -> None: |
| 19 | i = 0 |
| 20 | for char in self._plaintext: |
| 21 | self._ciphertext += chr(char ^ ord(self.key[i % self._key_length])) |
| 22 | i += 1 |
| 23 | |
| 24 | def _print_ciphertext(self) -> None: |
| 25 | from textwrap import TextWrapper |
| 26 | |
| 27 | wrapper = TextWrapper(width=56, initial_indent="\n") |
| 28 | xor_array = ("{ 0x" + |
| 29 | ", 0x".join(hex(ord(x))[2:].zfill(2).upper() |
| 30 | for x in self._ciphertext) + " };") |
| 31 | wrapped_xor_array = wrapper.fill(xor_array) |
| 32 | print(wrapped_xor_array) |
| 33 | |
| 34 | def run(self) -> None: |
| 35 | try: |
| 36 | with open(self._fname, "rb") as fp: |
| 37 | self._plaintext = fp.read() |
| 38 | except Exception as e: |
| 39 | print(f"[-] Error with specified file({self._fname}): {e}", |
| 40 | file=sys.stderr) |
| 41 | sys.exit(1) |
| 42 | else: |
| 43 | self._xor_crypt() |
| 44 | self._print_ciphertext() |
| 45 | return |
| 46 | |
| 47 | |
| 48 | def main(): |