Skip to content

Commit d02faf8

Browse files
committed
Added some codecs + Improved crack + Added GUI tool
1 parent 1c6f4e3 commit d02faf8

34 files changed

Lines changed: 2960 additions & 305 deletions

‎README.md‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,12 @@ $ echo "Test string !" | base91 | base85 | base36 | base58-flickr | unbase -f Te
108108
Test string !
109109
```
110110

111+
## :framed_picture: Usage (graphical tool)
112+
113+
`codext-gui` opens a window where a text or a file can be dropped to be guessed at once, with a cancellable search, recent and suggested patterns, and a light or dark theme following the system (drag-and-drop requires `pip install codext[gui]` ; otherwise, the text can be pasted or opened).
114+
115+
<p align="center"><img src="https://github.com/dhondta/python-codext/raw/main/docs/pages/img/gui.png" alt="Graphical tool" width="70%"/></p>
116+
111117
## :computer: Usage (CLI)
112118

113119
Listing codecs.
@@ -382,8 +388,8 @@ This category also contains `ascii85`, `adobe`, `[x]btoa`, `zeromq` with the `ba
382388
#### [Common](https://python-codext.readthedocs.io/en/latest/enc/common.html)
383389

384390
- [X] `a1z26`: keeps words whitespace-separated and uses a custom character separator
385-
- [X] `cases`: set of case-related encodings (including camel-, kebab-, lower-, pascal-, upper-, snake- and swap-case, slugify, capitalize, title)
386-
- [X] `dummy`: set of simple encodings (including integer, replace, reverse, word-reverse, substite and strip-spaces)
391+
- [X] `cases`: set of case-related encodings (including camel-, kebab-, lower-, pascal-, upper-, snake- and swap-case, slugify, capitalize, title, and case to bits)
392+
- [X] `dummy`: set of simple encodings (including integer, replace, reverse, word-reverse, substite, strip-spaces, tokenize, leftpad and rightpad)
387393
- [X] `octal`: dummy octal conversion (converts to 3-digits groups)
388394
- [X] `octal-spaced`: variant of `octal` ; dummy octal conversion, handling whitespace separators
389395
- [X] `ordinal`: dummy character ordinals conversion (converts to 3-digits groups)
@@ -409,11 +415,14 @@ This category also contains `ascii85`, `adobe`, `[x]btoa`, `zeromq` with the `ba
409415
- [X] `brainfuck`: well-known esoteric programming language (encoding generates a program printing the text)
410416
- [X] `church`: Church encoding in the lambda calculus (encoding generates a lambda term of the list of the numerals of the bytes)
411417
- [X] `cow`: esoteric language made of variations of "moo" (Brainfuck-like, with a register and integer output)
418+
- [X] `doubling-machine`: toy machine with an accumulator that is doubled, incremented, reset and output (encoding generates a program printing the text)
412419
- [X] `lolcode`: esoteric language inspired by lolcats (encoding generates a program printing the text), also with lowercase keywords
413420
- [X] `malbolge`: esoteric language designed to be as difficult to program in as possible (encoding generates a program printing the text)
414421
- [X] `ook`: Brainfuck derivative for orang-utans (`Ook.`, `Ook?` and `Ook!`), also in its short form
415422
- [X] `piet`: esoteric language whose programs are images looking like abstract paintings (encoding generates a PNG image of a program printing the text)
416423
- [X] `pikalang`: Brainfuck derivative using Pikachu's vocabulary
424+
- [X] `postfix`: tiny calculator in Reverse Polish Notation, also called `rpn` (encoding generates a program printing the text, also with an addition, a subtraction or a multiplication)
425+
- [X] `tiny-vm`: toy stack machine whose program is written in hexadecimal (encoding generates a program printing the text, also with an addition or a XOR)
417426

418427
#### [Frequency](https://python-codext.readthedocs.io/en/latest/enc/frequency.html)
419428

‎docs/pages/analysis.md‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,9 +73,21 @@ textness : 0.2051
7373
| `vigenere`, `beaufort`, `gronsfeld` | For each key length (up to 20 letters by default), each key letter is the shift of the corresponding letters (taken every key length letters) that distributes them the most as in a text ; the best keys are then refined letter by letter with the trigrams of the whole output |
7474
| `vernam` (repeating-key XOR) | The most likely key sizes (up to 32 characters by default) are the ones whose successive blocks are the closest in Hamming distance ; for each of them, each key character is the one that makes the corresponding characters look the most as a text |
7575
| `columnar` | All the orders of the columns are tried (brute force, up to 7 columns by default, i.e. 5913 orders), keeping the orders whose outputs hold the most common English trigrams |
76+
| `affine` | For each usual alphabet (`?l?u?s`, `?l?u`, `?l`, `?u`, ...) holding every letter of the ciphertext and whose cases of letters both show in it (a lowercase ciphertext does not come from `?l?u`), every pair of parameters `a,b` is rated by the letter frequencies of its output, then the best ones (all of them for a short ciphertext, e.g. a flag) as `crack` rates the outputs ; the other characters are left as is (e.g. the braces of a flag encoded with `errors="leave"`) |
7677
| any other codec | The encodings it lists for the guess mode are tried and ranked (e.g. `railfence-1` to `railfence-10`, `rot-1` to `rot-25`, `skip-1` to `skip-8`) |
7778

78-
The score is the mean of the textness of the output (as rated by the guess mode) and of the frequency of its trigrams in English texts (only the latter for an output without spaces, as the textness relies on words), weighted by the fit of its letter frequencies.
79+
The key recovery of a cipher is defined by its codec, as the `crack` function given to [`add` or `add_map`](howto.md#crack-function) ; `codext.crackable()` lists the codecs that define one:
80+
81+
```python
82+
>>> codext.crackable()
83+
['affine', 'beaufort', 'columnar', 'gronsfeld', 'vernam', 'vigenere']
84+
```
85+
86+
The score is the geometric mean of the textness of the output (as rated by the guess mode) and of the frequency of its trigrams in English texts (only the latter for an output without separators of words, i.e. spaces, underscores, hyphens or braces, as the textness relies on words), weighted by the fit of its letter frequencies. A flag (e.g. `demo{affine_crack3d}`) is also rated from its words (`demo affine cracked`), and favoured when its prefix is a usual one (e.g. `flag`, `CTF` or `HTB`). The characters that a cipher does not handle may have been left as is while encoding, hence they are also left as is when the strict decoding fails.
87+
88+
!!! tip "Short ciphertexts"
89+
90+
On a short ciphertext, e.g. a flag with an unusual prefix, the statistics may not tell the right key from a few wrong ones that happen to look as much like a text: the right output is then among the first ones, but not necessarily the first one. In the graphical tool, the outputs matching the pattern (e.g. the expected prefix of the flag) come first.
7991

8092
`crack` accepts the following arguments:
8193

‎docs/pages/cli.md‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,49 @@ usage examples:
7777

7878
`codext analyze` reports the statistical properties of the input (alphabet, randomness, letter frequencies, ...) with hints on what it may be, and `codext crack` recovers the key of a keyed cipher (e.g. `vigenere`, `vernam` or `columnar`) from the input ; see [Analysis and cracking](analysis.md).
7979

80+
### Graphical tool
81+
82+
`codext-gui` opens a window where a text, or a file, can be dropped to be guessed at once (as with `codext guess`). A text can also be pasted, or a file opened (*Open file...*), then guessed with the *Guess* button, and a text or a file can be given as argument (e.g. `codext-gui secret.txt`). The input and the output are shown side by side, above the search parameters and the results (the panes can be resized by dragging their separators). Below the input, a one-line summary tells its length and what it may be (from its [analysis](analysis.md), e.g. "It only holds hexadecimal characters"), and likewise below the output.
83+
84+
![Graphical tool](img/gui.png)
85+
86+
The chains of codecs found are listed with a preview of their outputs ; the output of the selected one is shown next to the input, and can be copied to the clipboard (*Copy*, or a double-click on the result), saved to a file as is (*Save...*, e.g. for binary data) or moved to the input with the left arrow between both areas (e.g. to decode it further) ; the right arrow shows the input in the output area, as the first result (*(input)*), e.g. to copy or save it.
87+
88+
Once the codec of every layer is set (see *Layers* below), the input can also be decoded with these codecs, in their order (*Decode*), or encoded with them, in the reverse order (*Encode*), so that decoding the result with the same layers gives the input back. Characters that a codec does not handle (e.g. the braces of a flag for a cipher on letters) are left as is, and the status bar tells which layers did so.
89+
90+
The search runs in a separate process, so that the window remains responsive and the search can be cancelled (the *Guess* button becomes *Cancel*), bounded by the timeout. It stops at the first output that matches the chosen condition (stop function):
91+
92+
- By default, it searches a single layer of encoding (*Layers*: 1, guessed) for the regular expression entered in the *Pattern* field (`regex` stop function), case-insensitive with *Ignore case*. The list of the field suggests common patterns (e.g. a flag format, a URL or an email address) and the recently used ones.
93+
- Without a pattern, the search looks for a natural language text (`text_strict` stop function) rather than failing.
94+
- The codecs considered can be restricted to some categories (*Codecs*, all by default) and to those whose names match a regular expression (*Codec names*, e.g. `base|rot`, or `^url$` for an exact name), within the selected categories ; the number of selected codecs is shown next to them. This speeds the search up when the kind of encoding is known (as `-i` does with `codext guess`).
95+
- The codec of each layer (in decoding order, the first being the outermost one) can be set, either picked from the list of codecs or typed with its parameters (e.g. `rot-13` or `xor-42`) ; typing the start of a name (e.g. `c`) lists the matching codecs below the field (from 3 characters or several words, the names holding them too, e.g. `fence` or `rot prog`), to be picked with *Up*/*Down* and *Enter* or a click (*Escape* closes the list), *Enter* also completing the name when a single codec matches, while the layers left to *(guess)* are guessed among the selected codecs. The solutions are then only searched once every set layer is decoded, the guessed layers after the last set one being optional (e.g. with 3 layers set to *(guess)*, `base64` and *(guess)*: a guessed layer, then Base64, then optionally another guessed layer). This speeds the search up a lot when some layers are known (as the `layers` parameter does with `codext.guess`).
96+
- *Rank* (*Ctrl+R*) shows how guessing ranks the codecs of the first layer that is not set yet (among the selected codecs), once the input is decoded with the layers set before it (or of the layer following them when every layer is set): a window lists the codecs that decode it, from the most probable one, with their scores (and a bar relative to the best one) and outputs. *Set as layer N* (or a double-click) sets the selected codec for this layer, e.g. to then rank the codecs of the next layer. As the search, the ranking can be cancelled (*Escape*) and stops at the timeout.
97+
- *Crack* (*Ctrl+K*) recovers the key of the cipher of the first layer set to a cipher without its key (e.g. `vigenere`, `affine`, `vernam`, `columnar`, or `railfence` whose encodings for the guess mode are tried), once the input is decoded with the layers set before it, as [`codext crack`](analysis.md#cracking) does: a window lists the most likely keys with the scores of their outputs (how much they look like a text), the outputs matching the *Pattern* (e.g. the prefix of a flag) coming first. *Set as layer N* (or a double-click) sets the selected encoding, with its key, for this layer. The key search stops at the timeout.
98+
- With *Find all matches*, the search does not stop at the first output that matches, but goes on until all the layers are explored or the timeout is reached, listing every match (as with `codext guess --do-not-stop`).
99+
- For an unknown chain of encodings, choose more layers ; the `text` stop function may stop at an intermediate encoding that looks like text (e.g. Base64), unlike `text_strict`.
100+
101+
| Shortcut | Action |
102+
| :--- | :--- |
103+
| Ctrl+Enter | Guess |
104+
| Escape | Cancel the search, the ranking or the cracking |
105+
| Ctrl+R | Rank the codecs of the first layer that is not set |
106+
| Ctrl+K | Crack the cipher of the first layer set to a cipher without its key |
107+
| Ctrl+O | Open a file |
108+
| Ctrl+L | Clear the input and the results |
109+
| Ctrl+A | Select all the text (a paste with Ctrl+V then replaces it) |
110+
| Ctrl+Shift+C | Copy the output of the selected result |
111+
| Ctrl+S | Save the output of the selected result |
112+
113+
The window follows the light or dark mode of the system (*Theme*: System), checked every few seconds, unless the light or dark theme is chosen. The mode of the system is read from the registry on Windows, from the global `AppleInterfaceStyle` setting on macOS and, on Linux, from the `GTK_THEME` environment variable, the color scheme or GTK theme of GNOME (`gsettings`) or the color scheme of KDE.
114+
115+
![Graphical tool in dark mode](img/gui-dark.png)
116+
117+
The settings (stop function, pattern, recent patterns, layers and their codecs, timeout, *Find all matches*, selected categories and codec names, theme and window size) are remembered between sessions, in `~/.codext-gui.json`.
118+
119+
!!! note "Optional dependencies"
120+
121+
The tool relies on Tkinter, part of the standard library but packaged separately on some systems (e.g. `sudo apt-get install python3-tk` on Debian/Ubuntu). Drag-and-drop requires the [`tkinterdnd2`](https://pypi.org/project/tkinterdnd2/) package, installed with `pip install codext[gui]` ; without it, the text can still be pasted or opened.
122+
80123
### Execution examples
81124

82125
**Scenario 1**: 2-stages encoded flag

‎docs/pages/comparison.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
| Size | 283 codecs (and 92 native Python codecs) in 15 categories, most of them with variants (e.g. `rot-1` to `rot-25`) ; 1279 encodings tried while guessing | 506 operations (encoding and decoding counted separately), of which about 300 for data formats, encodings, encryption, compression and hashing | 82 decoders | Over 900 tools (ciphers, but also mathematics, games and puzzles) |
1818
| Encodes and decodes | Both, with every codec | Both | Decodes only | Both, for most tools |
1919
| Automatic decoding of multiple layers | Yes: `guess`, a breadth-first search ordered by a ranking heuristic, with stop functions (text, flag, regex, natural language) and bounds (timeout, number of nodes, beam) | Yes: the *Magic* operation, which detects encodings with regular expressions, tries them and scores the outputs (magic bytes, UTF-8 validity, entropy, letter frequencies), up to a given depth | Yes: an A* search over its decoders, stopping at the first output that its checkers (English, regex cribs, known patterns, ...) consider as a plaintext | No: the *cipher identifier* (statistics and a neural network) suggests which tools to use, one layer at a time |
20-
| Keyed ciphers without the key | Key recovery on request (`crack`, `codext crack`) for Vigenère, Beaufort, Gronsfeld, repeating-key XOR and columnar transposition ; while guessing, only a fixed list of keys (e.g. `vigenere-key`, `vigenere-password`) | Single-byte XOR and bit rotations (*Magic* in intensive mode) | Yes, with crackers (e.g. Caesar, Vigenère, repeating-key XOR, monoalphabetic substitution) | Yes, for many classical ciphers (e.g. the Kasiski test for Vigenère) |
20+
| Keyed ciphers without the key | Key recovery on request (`crack`, `codext crack`) for Vigenère, Beaufort, Gronsfeld, repeating-key XOR, columnar transposition and affine ; while guessing, only a fixed list of keys (e.g. `vigenere-key`, `vigenere-password`) | Single-byte XOR and bit rotations (*Magic* in intensive mode) | Yes, with crackers (e.g. Caesar, Vigenère, repeating-key XOR, monoalphabetic substitution) | Yes, for many classical ciphers (e.g. the Kasiski test for Vigenère) |
2121
| Ranking of the candidate decodings | Yes (`rank`, `codext rank`) | No | No | Yes, for the identified ciphers |
2222
| Statistical analysis of the input | Yes (`analyze`, `codext analyze`): alphabet, randomness, file signature, hash lengths, repeated blocks, index of coincidence and letter frequencies | Yes (*Entropy*, *Frequency distribution*, *Chi Square*, *Index of Coincidence* operations) | No | Yes (*cipher identifier*, frequency analysis, index of coincidence) |
2323
| Strength of a chain of codecs | Yes (`strength`) and composition of a strong chain from assessment questions (`compose`) | No | No | No |

0 commit comments

Comments
 (0)