Skip to content

Commit 1cd16cb

Browse files
committed
Added codec: bazeries
1 parent 9872a23 commit 1cd16cb

4 files changed

Lines changed: 159 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,7 @@ This category also contains `ascii85`, `adobe`, `[x]btoa`, `zeromq` with the `ba
334334
- [X] `autoclave`: aka Autoclave/Autokey Cipher (variant of Vigenere Cipher)
335335
- [X] `bacon`: aka Baconian Cipher
336336
- [X] `barbie-N`: aka Barbie Typewriter (*N* belongs to [1, 4])
337+
- [X] `bazeries`: aka Bazeries Cipher (two Polybius grids and a transposition keyed by a number)
337338
- [X] `beaufort`: aka Beaufort Cipher (variant of Vigenere Cipher)
338339
- [X] `citrix`: aka Citrix CTX1 password encoding
339340
- [X] `playfair`: aka Playfair Cipher

‎docs/pages/enc/crypto.md‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,31 @@ It implements the cipher for its 4 different keys.
126126

127127
-----
128128

129+
### Bazeries Cipher
130+
131+
The Bazeries cipher, created by Etienne Bazeries, combines a transposition and a substitution with two Polybius grids, both driven by a number. The text is split into groups whose sizes are the digits of the number (repeated as needed), each group is reversed, and each letter is replaced by the letter at the same position in the second grid. The first grid holds the alphabet written in columns ; the second one is filled in rows with the number written in English words (e.g. `23` gives `TWENTY THREE`), or with an optional keyword, followed by the remaining letters.
132+
133+
**Codec** | **Conversions** | **Aliases** | **Comment**
134+
:---: | :---: | --- | ---
135+
`bazeries` | text <-> Bazeries ciphertext | `bazeries-23`, `bazeries_cipher-81257`, `bazeries-23-keyword`, `bazeries-12,3`, `bazeries-23-5-wv`, `bazeries-42-6` | Number required ; comma-separated group sizes for groups of 10 letters or more ; 5x5 grid by default, with `J` normalized to `I` (`5-XY` replaces *X* by *Y* instead) ; 6x6 grid (letters and digits, uppercase output) with `6` ; other characters and the case (5x5 grid only) are kept
136+
137+
```python
138+
>>> codext.encode("DCODE", "bazeries-23")
139+
'DLSLO'
140+
>>> codext.decode("DLSLO", "bazeries-23")
141+
'DCODE'
142+
>>> codext.encode("Simple substitution plus transposition", "bazeries-81257")
143+
'Xrmgqn brykrbkxkbkr xgqw cbrcqrweukcbw'
144+
>>> codext.encode("DCODE", "bazeries-23-keyword")
145+
'FMTMP'
146+
>>> codext.encode("ATTACKATDAWNTHENRETREAT", "bazeries-12,3")
147+
'CYOIMOSAOMMOQBMMOQWMQWC'
148+
>>> codext.encode("Test 1234!", "bazeries-42-6")
149+
'DTXD 2UW8!'
150+
```
151+
152+
-----
153+
129154
### Beaufort Cipher
130155

131156
This is a variant of the [Vigenere Cipher](#vigenere-cipher). There is no default key, meaning that `beaufort` as the encoding scheme throws a `LookupError` indicating that the _key must be a non-empty alphabetic string_.

‎src/codext/crypto/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from .atbash import *
44
from .bacon import *
55
from .barbie import *
6+
from .bazeries import *
67
from .citrix import *
78
from .playfair import *
89
from .phillips import *

‎src/codext/crypto/bazeries.py‎

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
# -*- coding: UTF-8 -*-
2+
"""Bazeries Cipher Codec - bazeries content encoding.
3+
4+
The Bazeries cipher is an encryption system created by Etienne Bazeries that combines two Polybius grids and a
5+
transposition based on a numeric key. The first grid holds the alphabet written in columns, the second one is filled in
6+
rows with the key number written in (English) words, or with a keyword, followed by the remaining letters. The
7+
plaintext is split into groups whose sizes are the digits of the key (repeated as needed), each group is reversed, and
8+
each letter is then replaced by the letter at the same position in the second grid.
9+
10+
This codec:
11+
- en/decodes strings from str to str
12+
- en/decodes strings from bytes to bytes
13+
- decodes file content to str (read)
14+
- encodes file content from str to bytes (write)
15+
16+
Reference: https://www.dcode.fr/bazeries-cipher
17+
"""
18+
from string import ascii_uppercase as UC, digits as DG
19+
20+
from ..__common__ import *
21+
22+
23+
__examples__ = {
24+
'enc(bazeries)': None,
25+
'enc(bazeries-0)': None,
26+
'enc(bazeries-23-6-ji)': None,
27+
'enc(bazeries-23-5-jj)': None,
28+
'enc(bazeries-23)': {'DCODE': "DLSLO", 'dcode': "dlslo"},
29+
'dec(bazeries-23)': {'DLSLO': "DCODE"},
30+
'enc(bazeries_cipher-81257)': {'SIMPLE SUBSTITUTION PLUS TRANSPOSITION':
31+
"XRMGQN BRYKRBKXKBKR XGQW CBRCQRWEUKCBW"},
32+
'enc(bazeries-23-keyword)': {'DCODE': "FMTMP"},
33+
'enc(bazeries-12,3)': {'ABCDEFGHIJKLMNOPQRS': "ESKKBRNQIADOLCTFWHV"},
34+
'enc(bazeries-42-6)': {'Test 1234!': "DTXD 2UW8!"},
35+
'enc-dec(bazeries-137)': ["HELLO", "Hello, World!", "Test 1234!", "Café, ñandú & 10€"],
36+
'enc-dec(bazeries-3752-jumping)': ["ATTACK AT DAWN", "This is a test"],
37+
'enc-dec(bazeries-1002003)': ["ATTACK AT DAWN"],
38+
'enc-dec(bazeries-105-5-wv)': ["THIS IS A TEST JUST AS IT IS"],
39+
'enc-dec(bazeries-42-6)': ["TEST 1234!", "THE CODE IS 0042"],
40+
}
41+
__guess__ = []
42+
43+
44+
_ONES = ["ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "ELEVEN", "TWELVE",
45+
"THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"]
46+
_TENS = [None, None, "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"]
47+
_SCALES = [(10**9, "BILLION"), (10**6, "MILLION"), (1000, "THOUSAND"), (100, "HUNDRED")]
48+
49+
50+
def __n2w(n):
51+
""" Convert a non-negative integer to its English words representation (uppercase). """
52+
if n < 20:
53+
return _ONES[n]
54+
if n < 100:
55+
return _TENS[n // 10] + ("" if (r := n % 10) == 0 else " " + _ONES[r])
56+
for s, w in _SCALES:
57+
if n >= s:
58+
return __n2w(n // s) + " " + w + ("" if (r := n % s) == 0 else " " + __n2w(r))
59+
60+
61+
def __build_grids(number, key, grid_size, replace_char):
62+
""" Build the substitution maps between the first grid (alphabet in columns) and the second grid (keyword or number
63+
in words, then the remaining letters, in rows). """
64+
alphabet = UC.replace(replace_char[0], "") if grid_size == 5 else UC + DG
65+
# the first grid is filled in columns, hence position i in rows holds the letter at index (i % n) * n + i // n
66+
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)
74+
return dict(zip(g1, g2)), dict(zip(g2, g1))
75+
76+
77+
def __set_params(numkey, key, grid_size, replace_char):
78+
numkey = str(numkey or "")
79+
if not re.match(r"^\d+(?:,\d+)*$", numkey):
80+
raise LookupError("Bad parameter for encoding 'bazeries': numeric key must be given")
81+
# group sizes are the digits of the key or, when separated by commas, the given numbers ; null sizes are ignored
82+
sizes = [s for s in map(int, numkey.split(",") if "," in numkey else numkey) if s > 0]
83+
if len(sizes) == 0:
84+
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
91+
92+
93+
def __bazeries(decode=False):
94+
def _wrapper(numkey=None, key=None, grid_size=None, replace_char=None):
95+
# bad parameters are only reported when coding, as the lookup of the bare codec name must succeed (e.g. when
96+
# listing the encodings)
97+
try:
98+
params = __set_params(numkey, key, grid_size, replace_char)
99+
except LookupError as e:
100+
params = e
101+
def _code(text, errors="strict"):
102+
if isinstance(params, LookupError):
103+
raise params
104+
sizes, maps, gsize, rchar = params
105+
smap = maps[decode]
106+
text = ensure_str(text)
107+
# only letters of the grid are transposed and substituted ; other characters and the case are kept in place
108+
slots, letters = [], []
109+
for i, c in enumerate(text):
110+
if (u := c.upper()) == rchar[0] and gsize == 5:
111+
u = rchar[1]
112+
if u in smap:
113+
slots.append(i)
114+
letters.append(u)
115+
# reversing the groups is its own inverse and commutes with the substitution, hence the same code decodes
116+
result, i, j = list(text), 0, 0
117+
while i < len(letters):
118+
group = letters[i:i+sizes[j % len(sizes)]]
119+
for k, c in enumerate(group[::-1]):
120+
pos, c = slots[i + k], smap[c]
121+
# with a 6x6 grid, a letter may be substituted by a digit, which cannot hold its case
122+
result[pos] = c.lower() if gsize == 5 and text[pos].islower() else c
123+
i += len(group)
124+
j += 1
125+
return (r := "".join(result)), len(r)
126+
return _code
127+
return _wrapper
128+
129+
130+
add("bazeries", __bazeries(), __bazeries(True),
131+
r"^bazeries(?:[-_]cipher)?(?:[-_](\d+(?:,\d+)*))?(?:[-_]([a-zA-Z]+))?(?:[-_]([56])(?:[-_]([a-zA-Z]{2}))?)?$",
132+
printables_rate=1., penalty=.1)

0 commit comments

Comments
 (0)