Skip to content

Commit 3623408

Browse files
committed
Added codec: hill
1 parent b5dd2db commit 3623408

4 files changed

Lines changed: 131 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,7 @@ This category also contains `ascii85`, `adobe`, `[x]btoa`, `zeromq` with the `ba
342342
- [X] `citrix`: aka Citrix CTX1 password encoding
343343
- [X] `columnar`: aka Columnar Transposition Cipher (keyword-ordered columns ; a second keyword gives the double transposition)
344344
- [X] `gronsfeld`: aka Gronsfeld Cipher (variant of Vigenere Cipher with a numeric key)
345+
- [X] `hill`: aka Hill Cipher (blocks of letters multiplied by a key matrix modulo 26)
345346
- [X] `nihilist`: aka Nihilist Cipher (sums of the Polybius coordinates of the text and of a repeated key)
346347
- [X] `playfair`: aka Playfair Cipher
347348
- [X] `phillips`: aka Phillips Cipher (polyalphabetic block cipher with 8 key squares)

‎docs/pages/enc/crypto.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,25 @@ This is a variant of the [Vigenere Cipher](#vigenere-cipher) whose key is made o
273273

274274
-----
275275

276+
### Hill Cipher
277+
278+
The letters (A=0, ..., Z=25) are taken in blocks of n, each 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 length is a square (4 letters for a 2x2 matrix, 9 for a 3x3 matrix, ...), filled row by row ; it must be invertible modulo 26, that is, its determinant must be coprime with 26. Other characters are kept in place, as well as the case of the letters. When encoding, the last block is padded with "`X`", the padding letters being appended to the text.
279+
280+
**Codec** | **Conversions** | **Aliases** | **Comment**
281+
:---: | :---: | --- | ---
282+
`hill` | text <-> Hill ciphertext | `hill-ddcf`, `hill_cipher-gybnqkurp` | key length must be a square and the key matrix must be invertible modulo 26
283+
284+
```python
285+
>>> codext.encode("ACT", "hill-gybnqkurp")
286+
'POH'
287+
>>> codext.decode("POH", "hill-gybnqkurp")
288+
'ACT'
289+
>>> codext.encode("Cats!", "hill-gybnqkurp")
290+
'Finh!AE'
291+
```
292+
293+
-----
294+
276295
### Nihilist Cipher
277296

278297
Each letter of the text and of the key is replaced by its coordinates (row and column, from 1 to 5) in a 5x5 Polybius square (I and J sharing a cell), read as a two-digit number. The ciphertext is made of the sums of the numbers of the text and of the repeated key, separated by spaces. The square is filled with an optional keyword (without duplicates), then with the remaining letters of the alphabet. When encoding, whitespaces are ignored ; when decoding, the numbers are separated by whitespaces.

‎src/codext/crypto/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from .bifid import *
99
from .citrix import *
1010
from .columnar import *
11+
from .hill import *
1112
from .nihilist import *
1213
from .playfair import *
1314
from .phillips import *

‎src/codext/crypto/hill.py‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
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

Comments
 (0)