Skip to content

Commit f6cd1fa

Browse files
committed
Added codecs: foursquare, twosquare
1 parent 5035703 commit f6cd1fa

8 files changed

Lines changed: 289 additions & 50 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,6 +353,7 @@ This category also contains `ascii85`, `adobe`, `[x]btoa`, `zeromq` with the `ba
353353
- [X] `chaocipher`: aka Chaocipher (two alphabets permuted after each letter)
354354
- [X] `citrix`: aka Citrix CTX1 password encoding
355355
- [X] `columnar`: aka Columnar Transposition Cipher (keyword-ordered columns ; a second keyword gives the double transposition)
356+
- [X] `foursquare`: aka Four-square Cipher (bigrams substituted with two keyed squares and two plain ones)
356357
- [X] `gronsfeld`: aka Gronsfeld Cipher (variant of Vigenere Cipher with a numeric key)
357358
- [X] `hill`: aka Hill Cipher (blocks of letters multiplied by a key matrix modulo 26)
358359
- [X] `nihilist`: aka Nihilist Cipher (sums of the Polybius coordinates of the text and of a repeated key)
@@ -366,6 +367,7 @@ This category also contains `ascii85`, `adobe`, `[x]btoa`, `zeromq` with the `ba
366367
- [X] `shiftN`: shift ordinals (*N* belongs to [1,255])
367368
- [X] `skip`: aka Skip Cipher (transposition reading every N-th character, looping on the text)
368369
- [X] `trithemius`: aka Trithemius Cipher (variant of Vigenere Cipher)
370+
- [X] `twosquare`: aka Two-square Cipher or Double Playfair (bigrams substituted with two keyed squares, vertically or horizontally)
369371
- [X] `vic`: aka VIC Cipher
370372
- [X] `vigenere`: aka Vigenere Cipher
371373
- [X] `xorN`: XOR with a single byte (*N* belongs to [1,255])

‎docs/pages/enc/crypto.md‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,27 @@ The text is written in rows under a keyword, then read column by column, in the
275275

276276
-----
277277

278+
### Four-square Cipher
279+
280+
The Four-square cipher, invented by Felix Delastelle, substitutes pairs of letters using four squares arranged in a 2x2 matrix: the upper-left and lower-right ones hold the alphabet in order, while the upper-right and lower-left ones are filled with two keywords. The first letter of each pair is located in the upper-left square and the second one in the lower-right square ; they are replaced by the letters at the other corners of the rectangle they form (in the upper-right square, then in the lower-left one).
281+
282+
**Codec** | **Conversions** | **Aliases** | **Comment**
283+
:---: | :---: | --- | ---
284+
`foursquare` | text <-> Four-square ciphertext | `four-square-example-keyword`, `foursquare_cipher-key1-key2`, `foursquare-example-keyword-5-qk`, `foursquare-secret-key-6` | Two keywords required ; 5x5 squares by default, with `J` normalized to `I` (`5-XY` replaces *X* by *Y* instead) ; 6x6 squares (letters and digits) with `6` ; whitespace removed, uppercase output, padded with `X` to an even number of letters
285+
286+
```python
287+
>>> codext.encode("help me obi wan kenobi", "foursquare-example-keyword")
288+
'FYNFNEHWBXAFFOKHMD'
289+
>>> codext.decode("FYNFNEHWBXAFFOKHMD", "foursquare-example-keyword")
290+
'HELPMEOBIWANKENOBI'
291+
>>> codext.encode("help me obi wan kenobi", "foursquare-example-keyword-5-qk")
292+
'FYGMKYHOBXMFKKKIMD'
293+
>>> codext.encode("Hide the gold 2026", "foursquare-secret-key-6")
294+
'FFTAQFSIOGT1209T'
295+
```
296+
297+
-----
298+
278299
### Gronsfeld Cipher
279300

280301
This is a variant of the [Vigenere Cipher](#vigenere-cipher) whose key is made of digits, each digit giving the shift of a letter (0 to 9). There is no default key, meaning that `gronsfeld` as the encoding scheme throws a `LookupError` indicating that the _key must be a non-empty numeric string_.
@@ -497,6 +518,27 @@ This is a variant of the [Vigenere Cipher](#vigenere-cipher) with key `"ABCDEFGH
497518

498519
-----
499520

521+
### Two-square Cipher
522+
523+
The Two-square cipher (or Double Playfair), invented by Charles Wheatstone, substitutes pairs of letters using two squares filled with two keywords, placed one above the other (vertical, by default) or side by side (horizontal). The first letter of each pair is located in the first square and the second one in the second square ; they are replaced by the letters at the other corners of the rectangle they form. In the vertical variant, the output starts with the letter of the upper square and a pair whose letters share a column is left unchanged ; in the horizontal one, the output starts with the letter of the right square and a pair whose letters share a row is reversed.
524+
525+
**Codec** | **Conversions** | **Aliases** | **Comment**
526+
:---: | :---: | --- | ---
527+
`twosquare` | text <-> Two-square ciphertext | `two-square-example-keyword`, `double-playfair-key1-key2`, `twosquare-key-word-h`, `twosquare-key-word-horizontal-5-qk`, `twosquare-secret-key-v-6` | Two keywords required ; vertical (`v`, by default) or horizontal (`h`) ; 5x5 squares by default, with `J` normalized to `I` (`5-XY` replaces *X* by *Y* instead) ; 6x6 squares (letters and digits) with `6` ; whitespace removed, uppercase output, padded with `X` to an even number of letters
528+
529+
```python
530+
>>> codext.encode("help me obi wan kenobi", "twosquare-example-keyword")
531+
'HECMXWSRKYXPHWNODG'
532+
>>> codext.encode("help me obi wan kenobi", "twosquare-example-keyword-5-qk")
533+
'HEDLXWSDJYANHOTKDG'
534+
>>> codext.encode("DCODEZ", "twosquare-key-word-h")
535+
'CDLBAV'
536+
>>> codext.decode("CDLBAV", "twosquare-key-word-h")
537+
'DCODEZ'
538+
```
539+
540+
-----
541+
500542
### VIC Cipher
501543

502544
The VIC cipher combines a straddling checkerboard substitution (converting letters to a stream of digits) and an over-encryption based on a modulo-10 sum with eventually a conversion from digits to text.

‎src/codext/crypto/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from .chaocipher import *
1010
from .citrix import *
1111
from .columnar import *
12+
from .foursquare import *
1213
from .hill import *
1314
from .nihilist import *
1415
from .playfair import *
@@ -19,6 +20,7 @@
1920
from .scytale import *
2021
from .shift import *
2122
from .skip import *
23+
from .twosquare import *
2224
from .vic import *
2325
from .vigenere import *
2426
from .xor import *

‎src/codext/crypto/_square.py‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# -*- coding: UTF-8 -*-
2+
"""Keyed squares, shared by the ciphers of the Playfair family (Playfair, Two-square, Four-square) and Bazeries.
3+
4+
A square holds a 5x5 alphabet (a letter being replaced by another one, I and J sharing a cell by default) or a 6x6
5+
alphabet (letters and digits). It is filled row by row with the distinct letters of a keyword, then with the remaining
6+
ones of the alphabet.
7+
"""
8+
from string import ascii_uppercase as UC, digits as DG
9+
10+
from ..__common__ import ensure_str, handle_error
11+
12+
13+
def keyed_square(key, alphabet, replace=None):
14+
""" Fill a square, row by row, with the distinct characters of the key that belong to the alphabet (after replacing
15+
the given (letter, substitute) pair), then with the remaining ones of the alphabet. """
16+
seen, grid = set(), []
17+
for c in key.upper() + alphabet:
18+
if replace and c == replace[0]:
19+
c = replace[1]
20+
if c in alphabet and c not in seen:
21+
seen.add(c)
22+
grid.append(c)
23+
return grid
24+
25+
26+
def square_params(name, grid_size=None, replace_char=None):
27+
""" Check the grid size and the replaced pair of letters (only for a 5x5 grid, None otherwise), then get the
28+
alphabet. """
29+
gs = int(grid_size or 5)
30+
if gs == 6 and replace_char:
31+
raise LookupError(f"Bad parameter for encoding '{name}': replaced char only applies to a 5x5 grid")
32+
if len(rc := str(replace_char or "JI").upper()) != 2 or rc[0] == rc[1]:
33+
raise LookupError(f"Bad parameter for encoding '{name}': replaced char must be a pair of distinct letters")
34+
return (gs, tuple(rc), UC.replace(rc[0], "")) if gs == 5 else (gs, None, UC + DG)
35+
36+
37+
def digraph_codec(name, pair, alphabet, replace, decode=False):
38+
""" Make a codec function substituting the digraphs of the letters of the text with the given pair function.
39+
40+
The text is uppercased and its whitespace removed ; characters that are not in the alphabet are handled as errors
41+
and do not take part in the digraphs. When encoding, a text with an odd number of letters is padded with an
42+
"X". """
43+
def _code(text, errors="strict"):
44+
_h = handle_error(name, errors, decode=decode)
45+
out, slots, letters, where = [], [], [], []
46+
for i, c in enumerate("".join(ensure_str(text).upper().split())):
47+
if replace and c == replace[0]:
48+
c = replace[1]
49+
if c in alphabet:
50+
slots.append(len(out))
51+
letters.append(c)
52+
where.append(i)
53+
out.append(c)
54+
else:
55+
out.append(_h(c, i))
56+
if len(letters) % 2:
57+
if decode:
58+
# a ciphertext always holds an even number of letters ; the last one is then handled as an error
59+
out[slots.pop()] = _h(letters.pop(), where[-1])
60+
else:
61+
slots.append(len(out))
62+
letters.append(replace[1] if replace and replace[0] == "X" else "X")
63+
out.append(None)
64+
for k in range(0, len(letters), 2):
65+
out[slots[k]], out[slots[k+1]] = pair(letters[k], letters[k+1])
66+
return (r := "".join(out)), len(r)
67+
return _code

‎src/codext/crypto/bazeries.py‎

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,7 @@
1515
1616
Reference: https://www.dcode.fr/bazeries-cipher
1717
"""
18-
from string import ascii_uppercase as UC, digits as DG
19-
18+
from ._square import *
2019
from ..__common__ import *
2120

2221

@@ -58,19 +57,12 @@ def __n2w(n):
5857
return __n2w(n // s) + " " + w + ("" if (r := n % s) == 0 else " " + __n2w(r))
5958

6059

61-
def __build_grids(number, key, grid_size, replace_char):
60+
def __build_grids(number, key, alphabet, grid_size, replace_char):
6261
""" Build the substitution maps between the first grid (alphabet in columns) and the second grid (keyword or number
6362
in words, then the remaining letters, in rows). """
64-
alphabet = UC.replace(replace_char[0], "") if grid_size == 5 else UC + DG
6563
# the first grid is filled in columns, hence position i in rows holds the letter at index (i % n) * n + i // n
6664
g1 = [alphabet[(i % grid_size) * grid_size + i // grid_size] for i in range(grid_size ** 2)]
67-
seen, g2 = set(), []
68-
for c in (key or __n2w(number)).upper() + alphabet:
69-
if grid_size == 5 and c == replace_char[0]:
70-
c = replace_char[1]
71-
if c in alphabet and c not in seen:
72-
seen.add(c)
73-
g2.append(c)
65+
g2 = keyed_square(key or __n2w(number), alphabet, replace_char)
7466
return dict(zip(g1, g2)), dict(zip(g2, g1))
7567

7668

@@ -82,12 +74,8 @@ def __set_params(numkey, key, grid_size, replace_char):
8274
sizes = [s for s in map(int, numkey.split(",") if "," in numkey else numkey) if s > 0]
8375
if len(sizes) == 0:
8476
raise LookupError("Bad parameter for encoding 'bazeries': numeric key must hold at least one non-null group size")
85-
gs = int(grid_size or 5)
86-
if gs == 6 and replace_char:
87-
raise LookupError("Bad parameter for encoding 'bazeries': replaced char only applies to a 5x5 grid")
88-
if len(rc := str(replace_char or "JI").upper()) != 2 or rc[0] == rc[1]:
89-
raise LookupError("Bad parameter for encoding 'bazeries': replaced char must be a pair of distinct letters")
90-
return sizes, __build_grids(int(numkey.replace(",", "")), key, gs, rc), gs, rc
77+
gs, rc, alphabet = square_params("bazeries", grid_size, replace_char)
78+
return sizes, __build_grids(int(numkey.replace(",", "")), key, alphabet, gs, rc), gs, rc
9179

9280

9381
def __bazeries(decode=False):
@@ -107,7 +95,8 @@ def _code(text, errors="strict"):
10795
# only letters of the grid are transposed and substituted ; other characters and the case are kept in place
10896
slots, letters = [], []
10997
for i, c in enumerate(text):
110-
if (u := c.upper()) == rchar[0] and gsize == 5:
98+
u = c.upper()
99+
if rchar and u == rchar[0]:
111100
u = rchar[1]
112101
if u in smap:
113102
slots.append(i)

‎src/codext/crypto/foursquare.py‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# -*- coding: UTF-8 -*-
2+
"""Four-square Cipher Codec - four-square content encoding.
3+
4+
The Four-square cipher is a symmetric encryption method using polygram substitution with bigrams (pairs of letters),
5+
invented by Felix Delastelle. It relies on four squares arranged in a 2x2 matrix: the upper-left and lower-right ones
6+
hold the alphabet in order, while the upper-right and lower-left ones are filled with two keywords. For each pair, the
7+
first letter is located in the upper-left square and the second one in the lower-right square ; they are replaced by
8+
the letters at the other corners of the rectangle they form, that is, the letter of the upper-right square in the row
9+
of the first letter, then the letter of the lower-left square in the row of the second letter.
10+
11+
The 5x5 squares (I and J sharing a cell by default) or the 6x6 squares (letters and digits) can be used, with the
12+
replaced pair of letters being configurable in the codec name. Whitespace is removed and a text with an odd number of
13+
letters is padded with an "X".
14+
15+
This codec:
16+
- en/decodes strings from str to str
17+
- en/decodes strings from bytes to bytes
18+
- decodes file content to str (read)
19+
- encodes file content from str to bytes (write)
20+
21+
Reference: https://en.wikipedia.org/wiki/Four-square_cipher
22+
"""
23+
from ._square import *
24+
from ..__common__ import *
25+
26+
27+
__examples__ = {
28+
'enc(foursquare)': None,
29+
'enc(foursquare-example)': None,
30+
'enc(foursquare-example-keyword-6-ji)': None,
31+
'enc(foursquare-example-keyword-5-jj)': None,
32+
'enc(four-square-example-keyword-5-qk)': {'help me obi wan kenobi': "FYGMKYHOBXMFKKKIMD"},
33+
'dec(four_square-example-keyword-5-qk)': {'FYGMKYHOBXMFKKKIMD': "HELPMEOBIWANKENOBI"},
34+
'enc(foursquare_cipher-example-keyword)': {'Test!': None, 'TEST': "TWSP", 'TES': "TWRV",
35+
'JUNK': "FQNA", 'IUNK': "FQNA"},
36+
'dec(foursquare_cipher-example-keyword)': {'SAQ': None, 'SA?T': None},
37+
'enc(foursquare-example-keyword-5-xy)': {'A': "MS", 'AY': "MS"},
38+
'enc(foursquare-secret-key-6)': {'JUNK MAIL 42': "FUNFJKIG8X"},
39+
'enc-dec(foursquare-example-keyword)': ["HELPMEOBIWANKENOBI", "ATTACKATDAWN"],
40+
'enc-dec(foursquare-secret-key-6)': ["JUNKMAIL42", "HIDEGOLD2026"],
41+
'enc-dec(foursquare-example-keyword-5-wv)': ["ITISJUSTATESTAGAIN"],
42+
}
43+
__guess__ = []
44+
45+
46+
def __foursquare(decode=False):
47+
def _wrapper(key1=None, key2=None, grid_size=None, replace_char=None):
48+
# bad parameters are only reported when coding, as the lookup of the bare codec name must succeed (e.g. when
49+
# listing the encodings)
50+
try:
51+
if not key1 or not key2:
52+
raise LookupError("Bad parameter for encoding 'foursquare': two keywords must be given")
53+
n, rc, alphabet = square_params("foursquare", grid_size, replace_char)
54+
except LookupError as e:
55+
err = e
56+
def _code(text, errors="strict"):
57+
raise err
58+
return _code
59+
# plaintext squares (upper-left and lower-right) and ciphertext squares (upper-right and lower-left)
60+
sq1, sq2 = keyed_square(key1, alphabet, rc), keyed_square(key2, alphabet, rc)
61+
p, p1, p2 = [{c: divmod(i, n) for i, c in enumerate(sq)} for sq in (alphabet, sq1, sq2)]
62+
def _pair(a, b):
63+
if decode:
64+
(r1, c2), (r2, c1) = p1[a], p2[b]
65+
return alphabet[r1 * n + c1], alphabet[r2 * n + c2]
66+
(r1, c1), (r2, c2) = p[a], p[b]
67+
return sq1[r1 * n + c2], sq2[r2 * n + c1]
68+
return digraph_codec("foursquare", _pair, alphabet, rc, decode)
69+
return _wrapper
70+
71+
72+
add("foursquare", __foursquare(), __foursquare(True),
73+
r"^four[-_]?square(?:[-_]cipher)?(?:[-_]([a-zA-Z]+))?(?:[-_]([a-zA-Z]+))?(?:[-_]([56])(?:[-_]([a-zA-Z]{2}))?)?$",
74+
printables_rate=1., penalty=.1)

‎src/codext/crypto/playfair.py‎

Lines changed: 13 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,7 @@
1919
2020
Reference: https://www.dcode.fr/playfair-cipher
2121
"""
22-
from string import ascii_uppercase as UC, digits as DG
23-
22+
from ._square import *
2423
from ..__common__ import *
2524

2625

@@ -42,47 +41,29 @@
4241
}
4342
__guess__ = ["playfair"]
4443

45-
_DEFAULT_ALPHABET = {
46-
5: UC.replace("J", ""),
47-
6: UC + DG,
48-
}
49-
5044

51-
def __build_grid(key=None, grid_size=5, replace_char=('J', 'I')):
52-
"""Build the Playfair grid from an optional keyword. """
53-
seen, grid = set(), []
54-
for c in key.upper():
55-
if grid_size == 5 and c == replace_char[0]:
56-
c = replace_char[1]
57-
if c.isalpha() and c not in seen:
58-
seen.add(c)
59-
grid.append(c)
60-
for c in _DEFAULT_ALPHABET[grid_size]:
61-
if c not in seen:
62-
seen.add(c)
63-
grid.append(c)
64-
return grid, {grid[i]: (i // grid_size, i % grid_size) for i in range(grid_size ** 2)}
45+
def __build_grid(key, alphabet, grid_size, replace_char):
46+
"""Build the Playfair grid from a keyword. """
47+
grid = keyed_square(key, alphabet, replace_char)
48+
return grid, {c: divmod(i, grid_size) for i, c in enumerate(grid)}
6549

6650

6751
def __set_params(key, grid_size, fill_chars, replace_char):
6852
if len(fc := str(fill_chars or "XQ").upper()) == 2 and fc[0] == fc[1]:
6953
raise LookupError("Bad parameter for encoding 'playfair': filling char must be a single letter or a pair of "
7054
"distinct letters")
71-
if len(rc := str(replace_char or "JI").upper()) == 2 and rc[0] == rc[1]:
72-
raise LookupError("Bad parameter for encoding 'playfair': replaced char must be a pair of distinct letters")
73-
gs = int(grid_size or 5)
74-
a = _DEFAULT_ALPHABET[gs]
55+
gs, rc, a = square_params("playfair", grid_size, replace_char)
7556
if len(fc) == 1:
7657
fc += a[(a.index(fc[0])+1) % len(a)]
77-
return (a if key == "*" else a[::-1] if key == "^" else key).upper(), gs, tuple(fc), tuple(rc)
58+
return (a if key == "*" else a[::-1] if key == "^" else key).upper(), a, gs, tuple(fc), rc
7859

7960

8061
def playfair_encode(key=None, grid_size=None, fill_chars=None, replace_char=None):
81-
key, gsize, fchars, rchar = __set_params(key, grid_size, fill_chars, replace_char)
82-
grid, pos = __build_grid(key, gsize, rchar)
62+
key, alphabet, gsize, fchars, rchar = __set_params(key, grid_size, fill_chars, replace_char)
63+
grid, pos = __build_grid(key, alphabet, gsize, rchar)
8364
def encode(text, errors="strict"):
8465
_filler = lambda c: fchars[1] if c == fchars[0] else fchars[0]
85-
chars = [rchar[1] if gsize == 5 and c == rchar[0] else c for c in ensure_str(text).upper().replace(" ", "")]
66+
chars = [rchar[1] if rchar and c == rchar[0] else c for c in ensure_str(text).upper().replace(" ", "")]
8667
result, i, _h = [], 0, handle_error("playfair", errors)
8768
while i < len(chars):
8869
a = chars[i]
@@ -113,10 +94,10 @@ def encode(text, errors="strict"):
11394

11495

11596
def playfair_decode(key=None, grid_size=None, fill_chars=None, replace_char=None):
116-
key, gsize, _, rchar = __set_params(key, grid_size, fill_chars, replace_char)
117-
grid, pos = __build_grid(key, gsize, rchar)
97+
key, alphabet, gsize, _, rchar = __set_params(key, grid_size, fill_chars, replace_char)
98+
grid, pos = __build_grid(key, alphabet, gsize, rchar)
11899
def decode(text, errors="strict"):
119-
chars = [rchar[1] if gsize == 5 and c == rchar[0] else c for c in ensure_str(text)]
100+
chars = [rchar[1] if rchar and c == rchar[0] else c for c in ensure_str(text)]
120101
result, i, _h = [], 0, handle_error("playfair", errors, decode=True)
121102
while i < len(chars):
122103
try:

0 commit comments

Comments
 (0)