## Hill cipher in Sage

Let’s first consider how Hill cipher encryption is commonly presented in introductory texts on cryptography or even Wikipedia. Let ${M}$ be a ${3 \times 3}$ invertible matrix over ${\mathbf{Z}_{26}}$ and let ${P}$ be a ${3 \times n}$ matrix also over ${\mathbf{Z}_{26}}$. We call ${M}$ the encryption key and ${P}$ is referred to as the plaintext. The ciphertext ${C}$ corresponding to ${P}$ is given by

$\displaystyle C = MP \pmod{26}.$

According to this scheme of encryption, given

$\displaystyle M = \begin{bmatrix} 6 & 24 & 1 \\ 13 & 16 & 10 \\ 20 & 17 & 15 \end{bmatrix} \ \ \ \ \ (1)$

and

$\displaystyle P = \begin{bmatrix} 0 \\ 2 \\ 19 \end{bmatrix} \ \ \ \ \ (2)$

then the ciphertext is

$\displaystyle C = \begin{bmatrix} 6 & 24 & 1 \\ 13 & 16 & 10 \\ 20 & 17 & 15 \end{bmatrix} \begin{bmatrix} 0 \\ 2 \\ 19 \end{bmatrix} = \begin{bmatrix} 15 \\ 14 \\ 7 \end{bmatrix}.$

Hill cipher encryption in Sage works differently from that presented above. If ${M}$ is the encryption matrix key and ${P}$ is the plaintext matrix, then the ciphertext is the matrix ${PM}$. Here, ${M}$ is still a square (${3 \times 3}$) matrix and ${P}$ is an ${n \times 3}$ matrix where the entries are filled from left to right, top to bottom. According to this scheme of encryption, with ${M}$ and ${P}$ as in (1) and (2), respectively, we get

$\displaystyle C = P^T M = \begin{bmatrix} 0 & 2 & 19 \end{bmatrix} \begin{bmatrix} 6 & 24 & 1 \\ 13 & 16 & 10 \\ 20 & 17 & 15 \end{bmatrix} = \begin{bmatrix} 16 & 17 & 19 \end{bmatrix}.$

Or using Sage:

sage: version()
Sage Version 4.4.1, Release Date: 2010-05-02
sage: H = HillCryptosystem(AlphabeticStrings(), 3)
sage: M = Matrix(IntegerModRing(26), [[6,24,1], [13,16,10], [20,17,15]])
sage: P = H.encoding("ACT")
sage: H.enciphering(M, P)
QRT