|
| 1 | +# -*- coding: UTF-8 -*- |
| 2 | +"""Hill Cipher Codec - hill content encoding. |
| 3 | +
|
| 4 | +The Hill cipher was invented by Lester S. Hill in 1929. The letters (A=0, ..., Z=25) are taken in blocks of n, each |
| 5 | + block being multiplied (as a column vector) by a n x n key matrix modulo 26. The key matrix is given as a keyword whose |
| 6 | + length is a square (4 letters for a 2x2 matrix, 9 for a 3x3 matrix, ...), filled row by row ; it must be invertible |
| 7 | + modulo 26, that is, its determinant must be coprime with 26. |
| 8 | +
|
| 9 | +Other characters are kept in place, as well as the case of the letters. When encoding, the last block is padded with |
| 10 | + "X" ; when decoding, an incomplete last block cannot be decoded. |
| 11 | +
|
| 12 | +This codec: |
| 13 | +- en/decodes strings from str to str |
| 14 | +- en/decodes strings from bytes to bytes |
| 15 | +- decodes file content to str (read) |
| 16 | +- encodes file content from str to bytes (write) |
| 17 | +
|
| 18 | +Reference: https://en.wikipedia.org/wiki/Hill_cipher |
| 19 | +""" |
| 20 | +from math import gcd, isqrt |
| 21 | +from string import ascii_lowercase as LC, ascii_uppercase as UC |
| 22 | + |
| 23 | +from ..__common__ import * |
| 24 | + |
| 25 | + |
| 26 | +__examples__ = { |
| 27 | + 'enc(hill)': None, |
| 28 | + 'enc(hill-abc)': None, |
| 29 | + 'enc(hill-abcd)': None, |
| 30 | + 'enc(hill-gybnqkurp)': {'ACT': "POH", 'CAT': "FIN", 'Cat!': "Fin!", 'CATS': "FINHAE"}, |
| 31 | + 'dec(hill_cipher-gybnqkurp)': {'POH': "ACT", 'FIN': "CAT", 'FINE': None}, |
| 32 | + 'enc(hill-ddcf)': {'HELP': "HIAT"}, |
| 33 | + 'dec(hill-cipher-ddcf)': {'HIAT': "HELP"}, |
| 34 | + 'enc(hill-invertiblematrix)': None, |
| 35 | + 'enc(hill-aaab)': None, |
| 36 | + # texts of 12 letters, so that no padding is needed with 2x2, 3x3 and 4x4 matrices |
| 37 | + 'enc-dec(hill-ddcf|hill-gybnqkurp|hill-lesterhillcipher)': ["", "Hello, my World", "Attack at dawn!!"], |
| 38 | +} |
| 39 | +__guess__ = [] |
| 40 | + |
| 41 | + |
| 42 | +def __det(m): |
| 43 | + """ Exact integer determinant with the fraction-free Bareiss algorithm. """ |
| 44 | + m, n, sign, prev = [r[:] for r in m], len(m), 1, 1 |
| 45 | + for k in range(n - 1): |
| 46 | + if m[k][k] == 0: |
| 47 | + for i in range(k + 1, n): |
| 48 | + if m[i][k] != 0: |
| 49 | + m[k], m[i], sign = m[i], m[k], -sign |
| 50 | + break |
| 51 | + else: |
| 52 | + return 0 |
| 53 | + for i in range(k + 1, n): |
| 54 | + for j in range(k + 1, n): |
| 55 | + m[i][j] = (m[i][j] * m[k][k] - m[i][k] * m[k][j]) // prev |
| 56 | + prev = m[k][k] |
| 57 | + return sign * m[-1][-1] |
| 58 | + |
| 59 | + |
| 60 | +def __set_params(key): |
| 61 | + key = str(key or "").upper() |
| 62 | + if (n := isqrt(len(key))) == 0 or n * n != len(key): |
| 63 | + raise LookupError("Bad parameter for encoding 'hill': key length must be a non-null square (4, 9, 16, ...)") |
| 64 | + m = [[ord(c) - 65 for c in key[i*n:(i+1)*n]] for i in range(n)] |
| 65 | + if gcd(d := __det(m) % 26, 26) != 1: |
| 66 | + raise LookupError("Bad parameter for encoding 'hill': key matrix must be invertible modulo 26") |
| 67 | + # inverse matrix: inverse of the determinant times the adjugate (transposed cofactors) |
| 68 | + minor = lambda i, j: [r[:j] + r[j+1:] for k, r in enumerate(m) if k != i] |
| 69 | + adj = [[(-1) ** (i + j) * __det(minor(j, i)) if n > 1 else 1 for j in range(n)] for i in range(n)] |
| 70 | + return m, [[pow(d, -1, 26) * x % 26 for x in r] for r in adj] |
| 71 | + |
| 72 | + |
| 73 | +def __hill(decode=False): |
| 74 | + def _wrapper(key=None): |
| 75 | + # bad parameters are only reported when coding, as the lookup of the bare codec name must succeed (e.g. when |
| 76 | + # listing the encodings) |
| 77 | + try: |
| 78 | + params = __set_params(key) |
| 79 | + except LookupError as e: |
| 80 | + params = e |
| 81 | + def _code(text, errors="strict"): |
| 82 | + if isinstance(params, LookupError): |
| 83 | + raise params |
| 84 | + m = params[decode] |
| 85 | + n, text = len(m), ensure_str(text) |
| 86 | + slots = [i for i, c in enumerate(text) if c in LC or c in UC] |
| 87 | + values = [ord(text[i].upper()) - 65 for i in slots] |
| 88 | + r, l = list(text), len(values) - len(values) % n |
| 89 | + if not decode and l < len(values): |
| 90 | + # the last block is padded with "X", appended to the text |
| 91 | + values += [23] * (n - len(values) + l) |
| 92 | + l = len(values) |
| 93 | + out = [] |
| 94 | + for b in range(0, l, n): |
| 95 | + out += [sum(m[i][j] * values[b+j] for j in range(n)) % 26 for i in range(n)] |
| 96 | + for k, v in enumerate(out): |
| 97 | + if k < len(slots): |
| 98 | + r[slots[k]] = (LC if text[slots[k]] in LC else UC)[v] |
| 99 | + else: |
| 100 | + r.append(UC[v]) |
| 101 | + # an incomplete last block cannot be decoded |
| 102 | + _h = handle_error("hill", errors, decode=True) |
| 103 | + for k in slots[l:]: |
| 104 | + r[k] = _h(text[k], k, "".join(r[:k])) |
| 105 | + return (s := "".join(r)), len(s) |
| 106 | + return _code |
| 107 | + return _wrapper |
| 108 | + |
| 109 | + |
| 110 | +add("hill", __hill(), __hill(True), r"^hill(?:[-_]cipher)?(?:[-_]([a-zA-Z]+))?$", penalty=.1) |
0 commit comments