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:. (Related: Tech Report: Hugging Face Reads, Feb. 2021 - Long-range...)
In a recent development, 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.). (Related: Industry News: Deploy Hugging Face models easily with A...)
The classic Caesar cipher then falls right out:.
It has been revealed that 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).
Sources indicate that 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:.
Industry observers note that 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.
According to recent reports, 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.
Recent findings suggest that 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:.
In a recent development, 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:.
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:.
Sources indicate that 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.
According to recent reports, (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.