Classic Shift Ciphers with `lens` and `finite-typelits`
A good friend has been trolling me recently with a CTF-style treasure hunt, and some of the clues have been obscured behind classic shift ciphers. This has given me a chance to play with some of my favourite combinators from lens, as well as mess around with finite-typelits, which I’ve wanted to do for some time. The implementation of the ciphers turned out to be quite elegant, so I thought I’d write them up.
finite-typelits provides a Finite n type representing a number in the range [0..n-1], where n is a type-level natural, and a Num instance whose arithmetic is modulo n. Since many shift ciphers represent letters with A=0, B=1, …, Z=25, we can establish a useful mapping between Char and Finite 26. We have functions Finite 26 -> Char (turn the number back into a letter) and Char -> Maybe (Finite 26) (because some Chars are not uppercase letters). A Prism' is the optical way to keep them together:
_Upper :: Prism' Char (Finite 26)
_Upper = prism' (chr . (+ ord 'A') . fromIntegral . getFinite) $ \ch ->
if isAsciiUpper ch
then packFinite . fromIntegral $ ord ch - ord 'A'
else Nothing
prism' builds a Prism' from its component parts; getFinite turns any Finite n back into an Integer; and packFinite will return Nothing if its argument is out of range for the Finite n. (Veteran opticians might be tempted to use iso ord chr to factor out the Char <-> Int conversion, but then you can’t easily use isAsciiUpper, so I think the overall result is less clear.)
The classic Caesar cipher then falls right out:
caesar :: Integer -> Text -> Text
caesar key = each . _Upper +~ modulo key
each is a Traversal over “each element” of a structure. Here, it focuses each Char in a Text, but class Each also has instances that let it work over each Word8 in a ByteString or each element of a homogeneous tuple. Composing that with _Upper gives us a Traversal' Text (Finite 26) that looks at each uppercase Char in the Text, considered as a Finite 26. (Non-uppercase characters will be completely unaffected, and for the rest of the post I will pretend they don’t exist.) The (+~) operator adds its RHS to each focus of ASetter (Traversals are ASetters). To turn our Integer into a Finite 26 without failing or crashing, we use modulo, which computes the argument modulo 26 (including negatives).
ghci> caesar 13 "NGGNPX GUR RARZL NG QNJA"
"ATTACK THE ENEMY AT DAWN"
Another common cipher used in these games is the Vigenère cipher, which shifts each letter of the message by the corresponding letter in the key. This is a bit more complicated because it’s helpful to process the message as a list:
vigenere :: Text -> Text -> Text
vigenere key = partsOf (each . _Upper) %~ zipWith (+) (cycle key')
where
key' :: [Finite 26]
key' = key ^.. each . _Upper
partsOf is one of my favourite lens party tricks. Look past the scary type signature, and think of it as turning a Traversal s t a a into a Lens s t [a] [a] by collecting the Traversal’s foci into a list; the programmer makes a solemn promise not to change the number of elements in that list. The function on the RHS of (%~) has type [Finite 26] -> [Finite 26], where the argument is the letters of the message.
zipWith (+) combines the list of message letters with the list of key letters, but we need to be sure that it recurses through the entire message and doesn’t stop at the end of the key. cycle infinitely repeats the elements of a non-empty list, and key' = key ^.. each . _Upper gives us a list of uppercase letters in the Text key. cycle key' is then the infinitely repeating list of uppercase letters in key.
Decryption is the same as encryption, but subtracts the key instead of adding it. Subtracting a key is the same as adding a key where every letter has been inverted, so instead of subtracting a key "ABCDE" we add a key "AZYXW". This is done by traversing the uppercase letters of the key and using negate:
vigenereDecrypt :: Text -> Text -> Text
vigenereDecrypt key = vigenere $ key & each . _Upper %~ negate
ghci> vigenereDecrypt "COME ON AND SLAM" "CBP ASYCBPW EO FJS VEA"
"AND WELCOME TO THE JAM"
Once you have the message characters as a list, other transforms take little additional effort. Another challenge in the treasure hunt used a cipher I’ll call j, which added the ordinal position of each character to the message:
j :: Text -> Text -> Text
j key =
partsOf (each . _Upper) %~ zipWith3 combine [0 ..] (cycle key')
where
combine i k m = modulo (fromIntegral i) + k + m
key' = key ^.. each . _Upper
jDecrypt key = j $ key & error "...what goes here?"
Cipher j is interesting because it’s still fundamentally a Vigenère cipher. Adding the character’s index to the message is the same as shifting the message key by another key cycle ['A'..'Z']. Cipher j is therefore just a Vigenère cipher with a derived key, and the key’s period is at most the LCM of 26 and the input key. We can factor out the transformation of a j key into a Vigenère key, and simplify the implementation of both j and jDecrypt:
vigenereKeyOfJKey :: Text -> Text
vigenereKeyOfJKey key =
Text.pack . take period $
review _Upper <$> zipWith (+) (cycle key') (cycle finites)
where
key' = key ^.. each . _Upper
period = lcm (length key') 26
j :: Text -> Text -> Text
j = vigenere . vigenereKeyOfJKey
jDecrypt :: Text -> Text -> Text
jDecrypt = vigenereDecrypt . vigenereKeyOfJKey
key' is, as before, a list of the uppercase letters in key. finites is a list of every element of a Finite n, which also needs to be cycled. We zipWith (+) the two infinite lists together, take only the first period items (anything beyond that is a repeat of the derived key), and get a [Finite 26] representing the derived key. review reverses AReview (e.g. a Prism), so mapping review _Upper gives us back a [Char] which packs back into a Text.
(Could we have used String throughout this post and had an easier time with the infinite structures? Yes, except that vigenereKeyOfJKey would return an infinite list, which would be difficult to print if we needed. We’d also miss the chance to explore each on Text and the power of partsOf. If you didn’t like the lensing, reimplementing these ciphers using Strings could be a good exercise.)
None of this is Serious Cryptography™, but it’s been fun to write. finite-typelits is a cool little package, and I like that it uses GHC’s native type-level naturals instead of typelevel Peano numbers. lens remains undefeated as Haskell’s Swiss Army Knife of data structures, and makes Haskell a great choice for weekend hacks or small experiments.