|
| 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