Skip to content

Commit 1c6f4e3

Browse files
committed
Applied minor changes
1 parent ee726c2 commit 1c6f4e3

22 files changed

Lines changed: 1096 additions & 28 deletions

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
[![DOI](https://zenodo.org/badge/236679865.svg)](https://zenodo.org/badge/latestdoi/236679865)
1212
[![License](https://img.shields.io/pypi/l/codext.svg)](https://pypi.python.org/pypi/codext/)
1313

14-
[**CodExt**](https://github.com/dhondta/python-codext) is a library (Python 3.10 or later) that extends the native [`codecs`](https://docs.python.org/3/library/codecs) library (namely for adding new custom encodings and character mappings) and provides **150+ new codecs**, hence its name combining *CODecs EXTension*. It also features a **guess mode** for decoding multiple layers of encoding and **CLI tools** for convenience.
14+
[**CodExt**](https://github.com/dhondta/python-codext) is a library (Python 3.10 or later) that extends the native [`codecs`](https://docs.python.org/3/library/codecs) library (namely for adding new custom encodings and character mappings) and provides **150+ new codecs**, hence its name combining *CODecs EXTension*. It also features a **guess mode** for decoding multiple layers of encoding, the **analysis** of an input and the **cracking** of a few classical ciphers without their key, and **CLI tools** for convenience.
1515

1616
```sh
1717
$ pip install codext

‎docs/mkdocs.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ nav:
1010
- Home: index.md
1111
- Features: features.md
1212
- 'Guess mode': guessing.md
13+
- 'Analysis and cracking': analysis.md
1314
- Encodings:
1415
- Barcodes: enc/barcodes.md
1516
- Base: enc/base.md

‎docs/pages/analysis.md‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
Besides the [guess mode](guessing.md), which tries to reverse an unknown chain of encodings, `codext` can analyze an input, to tell what it may be before trying to decode it, and crack a keyed cipher whose key is unknown. Both features are inspired by [FeatherDuster](https://github.com/nccgroup/featherduster) and are independent of the guess mode, which does not use them.
2+
3+
-----
4+
5+
### Analysis
6+
7+
`analyze` reports the statistical properties of an input (`str` or `bytes`), with human-readable hints:
8+
9+
```python
10+
>>> import codext
11+
>>> r = codext.analyze("5d41402abc4b2a76b9719d911017c592")
12+
>>> r['alphabet'], r['hashes']
13+
('hexadecimal', 'MD4, MD5, NTLM')
14+
>>> r['hints']
15+
['It has the length of a hash digest (MD4, MD5, NTLM)', 'It only holds hexadecimal characters, hence it may be encoded with it']
16+
```
17+
18+
The properties are:
19+
20+
| Property | Description |
21+
| :--- | :--- |
22+
| `length` | Length in bytes (a `str` being taken as UTF-8) |
23+
| `alphabet` | Smallest known alphabet holding all the characters, whitespaces ignored (e.g. `binary digits`, `hexadecimal`, `Base32`, `Base64`, `printable characters`), or `None` |
24+
| `printables` | Rate of printable characters |
25+
| `entropy` | Shannon entropy of the bytes, in bits per byte (8 at most) |
26+
| `mean` | Mean of the bytes (127.5 for random data) |
27+
| `chi_square` | Chi-square of the distribution of the bytes (close to 255 for random data) |
28+
| `compression_ratio` | Length of the zlib compression divided by the length (close to or above 1 for random data) |
29+
| `longest_bit_run` | Length of the longest run of identical bits |
30+
| `monte_carlo_pi` | Monte Carlo estimate of Pi from the bytes (close to Pi for random data, as with the `ent` tool) |
31+
| `signature` | Format of the file signature the input starts with (e.g. `gzip`, `PNG`, `OpenSSL encrypted data`), or `None` |
32+
| `hashes` | Hashes whose digest has the length of the input (in bytes, or in hexadecimal characters), or `None` |
33+
| `repeated_blocks` | Numbers of repeated blocks by block size (8 or 16 bytes, when the length is a multiple of it), as a block cipher in ECB mode gives for repeated plaintext blocks |
34+
| `letters` | Number of Latin letters |
35+
| `index_of_coincidence` | Probability that two letters are equal (.0667 for English texts, .0385 for random letters) |
36+
| `letter_shift` | Shift N whose decoding (`rot-N`) distributes the letters the most as in a text, with how well they then fit the letter frequencies of a text (from 0 to 1, random letters fitting around .6) |
37+
| `key_length` | Estimated key length of a polyalphabetic substitution of the letters (e.g. Vigenère), or `None` |
38+
| `textness` | How much the input looks like a natural language text (from 0 to 1, as rated by the guess mode) |
39+
| `hints` | Human-readable interpretations of these properties |
40+
41+
For a ciphertext mostly made of letters, the hints tell the kind of classical cipher from the index of coincidence and the letter frequencies: a transposition (the letters are distributed as in a text but do not form words), a Caesar cipher (they are, once shifted), another monoalphabetic substitution (the index of coincidence is the one of a text, but no shift fits) or a polyalphabetic substitution (the letters are evenly distributed), with its likely key length. For binary data, they tell whether it looks random, that is, encrypted, random or compressed without a header: guessing an encoding is then unlikely to help.
42+
43+
From the terminal, the input is given with `-i` or through a pipe:
44+
45+
```session
46+
$ echo -en "It was a bright cold day in April, ..." | codext encode vigenere-rainbow | codext analyze
47+
length : 310
48+
alphabet : printable characters
49+
[...]
50+
index of coincidence : 0.0395
51+
letter shift : rot-8 (fit: 0.66)
52+
key length : 7
53+
textness : 0.2051
54+
55+
[*] Its letters are evenly distributed, as with a polyalphabetic substitution (e.g. vigenere) whose key would be 7 letters long.
56+
```
57+
58+
-----
59+
60+
### Cracking
61+
62+
`crack` recovers the most likely keys of a cipher for a ciphertext, decodes the ciphertext with each of them and ranks the outputs by how much they look like a text. It returns a list of `(score, encoding, output)` tuples, from the best score (1 at most):
63+
64+
```python
65+
>>> codext.crack("rglpxoiodltueosefdomerndat", "columnar", 2)
66+
[(0.8666666666666666, 'columnar-23541', 'ourfriendgoodoldsampletext'), (0.8249999999999998, 'columnar-25341', 'orufrinedgodooldasmplteext')]
67+
>>> codext.crack("SpTtmexale", "skip", 1)
68+
[(1.0, 'skip-3', 'SampleText')]
69+
```
70+
71+
| Cipher | Key recovery |
72+
| :--- | :--- |
73+
| `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 |
74+
| `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 |
75+
| `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+
| 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`) |
77+
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+
80+
`crack` accepts the following arguments:
81+
82+
- `limit`: maximum number of results (10 by default ; all of them if `None` or negative)
83+
- `max_key_length`: maximum key length (in letters, characters or columns, depending on the cipher)
84+
- `timeout`: maximum duration of the key search in seconds, then using the keys found so far
85+
86+
```session
87+
$ codext -i ciphertext.txt crack vigenere -l 2
88+
[+] 0.94140: vigenere-rainbow
89+
It was a bright cold day in April, and the clocks were striking thirteen....
90+
[+] 0.39865: vigenere-umfwrzpiharqxtmf
91+
Fh zrc p iabode trqy rbu as Sarom, xtx adm jnfxtb uxya sdcczrpl otetsson....
92+
```
93+
94+
With `-o`, the best output is written to the given file. Once the key is known, the encoding can also be given to the guess mode, e.g. `codext guess -i vigenere-rainbow`, for decoding the other layers.
95+
96+
!!! warning "Statistical attacks need enough ciphertext"
97+
98+
The key recovery relies on statistics, hence it needs enough ciphertext: a few tens of letters per key letter for a polyalphabetic substitution, a few blocks of the key size for repeating-key XOR. On a short ciphertext (e.g. "Jour toiglm cmoeetmku.", from `vigenere-rainbow`), the best output is a plausible-looking but wrong decoding. The trigrams are those of English texts, hence a text in another language gets lower scores.
99+
100+
!!! note "Not used by the guess mode"
101+
102+
Cracking runs only on request, for a given cipher: the guess mode keeps trying its fixed list of keys (e.g. `vigenere-key`, `vigenere-password`), as cracking every cipher at every step of its search would slow it down.

‎docs/pages/cli.md‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ optional arguments:
3636

3737
usage examples:
3838
- codext search bitcoin
39-
- codext decode base32 -i file.b32
39+
- codext -i file.b32 decode base32
4040
- codext encode morse < to_be_encoded.txt
4141
- echo "test" | codext encode base100
4242
- echo -en "test" | codext encode braille -o test.braille
@@ -53,6 +53,10 @@ usage examples:
5353
- codext compose -a alphanumeric -l 4 -k mysecret -m mychain -n
5454
- codext show rle
5555
- codext show base64-url rot-13 example-macro
56+
- codext -i secret.bin analyze
57+
- echo -en "test" | codext encode vigenere-rainbow | codext analyze
58+
- codext -i ciphertext.txt crack vigenere
59+
- echo -en "rglpxoiodltueosefdomerndat" | codext crack columnar -l 3
5660
```
5761

5862
!!! note "Input/output"
@@ -69,6 +73,10 @@ usage examples:
6973

7074
`codext show` displays the documentation of the given codecs, encodings or macros: the codec's name, category and module, then the docstring of this module (for a native codec, the one of its module from the `encodings` package), or the chain of encodings of a macro. An unknown name is reported with similar names (e.g. `codext show vigener` suggests `vigenere`).
7175

76+
!!! note "Analysis and cracking"
77+
78+
`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).
79+
7280
### Execution examples
7381

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

‎docs/pages/comparison.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@
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 | Only the keys tried while guessing (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 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) |
2121
| Ranking of the candidate decodings | Yes (`rank`, `codext rank`) | No | No | Yes, for the identified ciphers |
22+
| 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) |
2223
| Strength of a chain of codecs | Yes (`strength`) and composition of a strong chain from assessment questions (`compose`) | No | No | No |
2324
| Extensibility | New codecs from functions or character maps (`add`, `add_map`), macros (chains of codecs) | Recipes (chains of operations) ; new operations by contributing | New decoders by contributing | None |
2425

@@ -37,7 +38,7 @@ The counts are not directly comparable, as each tool counts different things:
3738

3839
### Strengths of each tool
3940

40-
- **codext** integrates with Python itself: once imported, its codecs are available through the native `codecs` module, including for reading and writing files. It encodes as well as it decodes, ranks the candidate decodings, and can evaluate and compose chains of codecs that resist guessing. It does not cover modern cryptography (e.g. AES, RSA) nor cryptanalysis of keyed ciphers.
41+
- **codext** integrates with Python itself: once imported, its codecs are available through the native `codecs` module, including for reading and writing files. It encodes as well as it decodes, ranks the candidate decodings, and can evaluate and compose chains of codecs that resist guessing. It can also analyze an input and recover the key of a few classical ciphers (`crack`), but does not cover modern cryptography (e.g. AES, RSA) nor most cryptanalysis of keyed ciphers.
4142
- **CyberChef** offers the broadest set of data manipulations beyond encodings (encryption, networking, forensics, multimedia) in a graphical interface where recipes are built by drag and drop, also usable from Node.js.
4243
- **Ciphey** focuses on decoding without any knowledge, including cracking keyed classical ciphers, and stops as soon as an output looks like a plaintext.
4344
- **dCode** covers the largest number of classical ciphers, with detailed explanations and solvers, but only online and one tool at a time.

‎docs/pages/enc/ciphers.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,8 @@ This writes each letter as a group of 5 symbols among two ("`a`" and "`b`"). It
161161
- the original 24-letter alphabet (default, or `bacon-24`), in which I and J, as well as U and V, share the same code (hence decoded as I and U) ;
162162
- the 26-letter alphabet (`bacon-26`), in which each letter has its own code (e.g. J is `abaab` and V is `babab`).
163163

164+
When the message is hidden in a cover text, each letter of this text carries one symbol, hence the spaces are the ones of the cover text and do not fall on the groups of 5 symbols. When decoding, if a space-separated group is not made of a multiple of 5 symbols, the spaces are removed and the last incomplete group (the remaining letters of the cover text) is ignored.
165+
164166
**Codec** | **Conversions** | **Aliases** | **Comment**
165167
:---: | :---: | --- | ---
166168
`bacon` | text <-> Bacon ciphertext | `bacon-cipher`, `baconian_cipher`, `bacon-01`, `bacon-10`, `bacon-26`, `bacon26-01` | Dynamic tokens mapping ; we can define a mapping of encoding's tokens (original tokens: `ab`), after the alphabet if any (e.g. `bacon-26-01`)
@@ -178,6 +180,8 @@ This writes each letter as a group of 5 symbols among two ("`a`" and "`b`"). It
178180
('abaabbabab', 'JV')
179181
>>> codext.decode("-..--..---.-...-..-. .-...-..-. ..... -..--..-..-..-.-..--", "bacon26_.-")
180182
'THIS IS A TEST'
183+
>>> codext.decode("BAAB AB AB AAABBBB AA BA A BAAABBAA BAAA BAAAAABA BAA A BAABAA BAABB AA", "bacon-26")
184+
'SUPERSECRET'
181185
```
182186

183187
-----

‎docs/pages/enc/common.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ This simple codec converts characters into their octal values.
2626
**Codec** | **Conversions** | **Aliases** | **Comment**
2727
:---: | :---: | --- | ---
2828
`octal` | text <-> octal digits | `octals` | groups of 3-chars octal values when encoded
29-
`octal-spaced` | text <-> spaced octal digits | `octals-spaced` | whitespace-separated suite of variable-length groups of octal digits when encoded
29+
`octal-spaced` | text <-> spaced octal digits | `octals-spaced` | whitespace-separated suite of variable-length groups of octal digits when encoded ; zero-padded groups (e.g. `040`, as given by `od -b`) are also accepted when decoding
3030

3131
```python
3232
>>> codext.encode("this is a test", "octal")
@@ -40,6 +40,8 @@ This simple codec converts characters into their octal values.
4040
'164 150 151 163 40 151 163 40 141 40 164 145 163 164'
4141
>>> codext.decode("164 150 151 163 40 151 163 40 141 40 164 145 163 164", "octals-spaced")
4242
'this is a test'
43+
>>> codext.decode("164 150 151 163 040 151 163 040 141 040 164 145 163 164", "octals-spaced")
44+
'this is a test'
4345
```
4446

4547
-----

0 commit comments

Comments
 (0)