Solitaire Cipher
January 18, 2011
Today’s exercise is straight forward but tedious; I will never admit the number of off-by-one errors I made while writing it. We will represent cards by the numbers 1 to 54, in bridge order, and letters by the numbers 1 to 26; it might be easier in both cases to use zero-based indices, because the modular arithmetic is more natural, but we will retain the conventions used by Schneier. A deck is a list of fifty-four card indices in positions 0 to 53. The function that converts a card number to its name is not needed elsewhere, but is given below because it is useful during debugging:
(define (name idx)
(define (pips idx)
(case (modulo (- idx 1) 13)
((0) "ace") ((1) "deuce") ((2) "trey")
((3) "four") ((4) "five") ((5) "six")
((6) "seven") ((7) "eight") ((8) "nine")
((9) "ten") ((10) "jack") ((11) "queen")
((12) "king")))
(define (suit idx)
(case (quotient (- idx 1) 13)
((0) "clubs") ((1) "diamonds")
((2) "hearts") ((3) "spades")))
(if (= idx 53) "little joker"
(if (= idx 54) "big joker"
(string-append (pips idx) " of " (suit idx)))))
The three functions shown below initialize a deck in bridge order, look up the value (card number) of a card at a particular deck position, and find the index in the deck of a given card number:
(define (init-deck) (range 1 55))
(define value list-ref) ; 1 <= value <= 54
(define (index deck val) ; 0 <= index <= 53
(let loop ((deck deck) (idx 0))
(if (= (car deck) val) idx
(loop (cdr deck) (+ idx 1)))))
The keystream generator takes a deck and produces a new deck in four steps. There is nothing hard about these functions, but all of the + 1 operations and the counts of the various deck positions are easy to get wrong:
(define (down-one deck idx)
(if (= idx 53)
(append (take 1 deck)
(list (value deck 53))
(take 52 (drop 1 deck)))
(append (take idx deck)
(list (value deck (+ idx 1)))
(list (value deck idx))
(drop (+ idx 2) deck))))
(define (down-two deck idx)
(cond ((= idx 53)
(append (take 2 deck)
(list (value deck 53))
(take 51 (drop 2 deck))))
((= idx 52)
(append (take 1 deck)
(list (value deck 52))
(take 51 (drop 1 deck))
(list (value deck 53))))
(else (append (take idx deck)
(take 2 (drop (+ idx 1) deck))
(list (value deck idx))
(drop (+ idx 3) deck)))))
(define (triple-cut deck)
(let* ((j1 (index deck 53))
(j2 (index deck 54))
(lo (min j1 j2))
(hi (max j1 j2)))
(append (drop (+ hi 1) deck)
(drop lo (take (+ hi 1) deck))
(take lo deck))))
(define (count-cut deck idx)
(append (take (- 53 idx)
(drop idx deck))
(take idx deck)
(list (value deck 53))))
(define (next-deck deck)
(let* ((d1 (down-one deck (index deck 53)))
(d2 (down-two d1 (index d1 54)))
(d3 (triple-cut d2)))
(count-cut d3 (min (value d3 53) 53))))
The key is pointed to by the top card in the deck. Either joker is represented as 53. If the key card is in the range 27 to 52, it is reduced by 26:
(define (card deck)
(let ((c (value deck (min (value deck 0) 53))))
(if (< 26 c 53) (- c 26) c)))
The procedure for keying the deck is given below. Schneier’s description of the operation is confusing. The thing to remember is that the deck is manipulated one time more than the number of characters in the key:
(define (key-deck key)
(let loop ((ks (prep key)) (deck (next-deck (init-deck))))
(if (null? ks) deck
(loop (cdr ks) (next-deck (count-cut deck (numb (car ks))))))))
Given what we already have, encrypt
and decrypt
are simple. The keystream and input text are processed in parallel, except that an extra element of the keystream is generated whenever a joker appears. The arithmetic to add and subtract letters is computed by the k
and p
variables:
(define (encrypt key plain-text)
(let* ((p (prep plain-text)) (len (modulo (length p) 5))
(ps (append p (make-list (if (zero? len) 0 (- 5 len)) #\X))))
(let loop ((ps ps) (deck (key-deck key)) (cs '()))
(if (null? ps) (list->string (fives (reverse cs)))
(if (< 52 (card deck)) (loop ps (next-deck deck) cs)
(let* ((k (+ (numb (car ps)) (card deck)))
(c (letr (if (< 26 k) (- k 26) k))))
(loop (cdr ps) (next-deck deck) (cons c cs))))))))
(define (decrypt key cipher-text)
(let loop ((cs (prep cipher-text)) (deck (key-deck key)) (ps '()))
(if (null? cs) (list->string (reverse ps))
(if (< 52 (card deck)) (loop cs (next-deck deck) ps)
(let* ((k (- (numb (car cs)) (card deck)))
(p (letr (if (< k 1) (+ k 26) k))))
(loop (cdr cs) (next-deck deck) (cons p ps)))))))
We used several utility functions. Prep
eliminates non-alphabetic characters from an input string and converts it to upper case. Numb
and letr
translate A=1 … Z=26. Fives
breaks its input into five-character blocks:
(define (prep str)
(map char-upcase
(filter char-alphabetic?
(string->list str))))
(define (numb letr) (- (char->integer letr) 64))
(define (letr numb) (integer->char (+ numb 64)))
(define (fives text)
(if (< (length text) 6) text
(append (take 5 text) (list #\space) (fives (drop 5 text)))))
For testing, we use sol-equal?
to check if two strings are equal after converting them to upper case and eliminating non-alphabetic characters and trailing nulls, rand-string
to generate random strings for keys and plaintext, and a modified version of the assert
macro that uses sol-equal?
instead of equal?
:
(define (sol-equal? s1 s2)
(define (del-x s)
(list->string (reverse
(drop-while (lambda (c) (char=? c #\X))
(reverse s)))))
(let ((p1 (del-x (prep s1))) (p2 (del-x (prep s2))))
(string=? p1 p2)))
(define (rand-string n)
(let loop ((n n) (cs '()))
(if (zero? n) (list->string cs)
(let* ((r (randint 27))
(c (if (zero? r) #\space (letr r))))
(loop (- n 1) (cons c cs))))))
Then the test performs Schneier’s three sample encryptions, and does a hundred round-trip checks through encryption and decryption with random keys and plaintext:
(define (sol-test)
(assert (encrypt "" "AAAAAAAAAA") "EXKYI ZSGEH")
(assert (decrypt "" "EXKYI ZSGEH") "AAAAAAAAAA")
(assert (encrypt "FOO" "AAAAAAAAAAAAAAA") "ITHZU JIWGR FARMW")
(assert (decrypt "FOO" "ITHZU JIWGR FARMW") "AAAAAAAAAAAAAAA")
(assert (encrypt "CRYPTONOMICON" "SOLITAIRE") "KIRAK SFJAN")
(assert (decrypt "CRYPTONOMICON" "KIRAK SFJAN") "SOLITAIRE")
(do ((i 0 (+ i 1))) ((= i 100))
(let ((key (rand-string 80)) (plain-text (rand-string 1000)))
(assert (decrypt key (encrypt key plain-text)) plain-text))))
Here it is in action:
> (encrypt "CRYPTONOMICON" "SOLITAIRE")
"KIRAK SFJAN"
We used take
, drop
, drop-while
, range
, filter
, make-list
from the Standard Prelude; testing also requires randint and a modified version of assert. You can run the program at http://programmingpraxis.codepad.org/PDJGeldx.
My Python solution:
Line 84 should be:
and not:
My solution (Haskell): https://gist.github.com/785960
My python version.
My attempt in scheme.
Another attempt using pattern matching.
Here is v. 0.0.1 of my writing of this algorithm. This is not neat and pretty, merely functional. The first block of code is solitaire.py. It executes when called on the console (only tested on UNIX-like systems) and must be passed arguments to work. There is a class and list of functions in solitaire.py. Deck class handles all the stuff you’d expect a deck in solitaire to handle: pushing cards, popping cards, getting characters, advancing state, and a built-in make. The functions in solitaire.py are mainly for loading and unloading deck states and to operate the command-line form.
Advpass option for command line operation is a demonstration of nested decks, basically a deck of decks. The deck class is flexible enough to take characters, strings, binary blobs, functions, or anything else that counts as an object as a card’s representation.
I wrote pyrand.py to interface to /dev/urandom and serve me up tasty 32-bit unsigned random integers. Replace in code with your own solution as I suspect pyrand is the slow spot in the shuffle routines in solitaire.py…
This is the first time this code has left this system, consider it licensed under BSD by:
Daniel Duffield
LucianSolaris@gmail.com
https://www.facebook.com/LucianSolaris
solitaire.py:
pyrand.py:
A bug was discovered in the functions pushCard(), pushAlpha(), and pushJoker(). They caused the deck to be loaded in the wrong order. The corrected code is below.
solitaire.py: (v. 0.0.2)
A couple more bugs squashed, one involving returning the last card counted instead of the next one after the last one counted. Now operates to real-life version.
Build deck file that resembles the standard hand-held algorithm by inputting:
Generate a key with:
Then open soldeck001.deck in a text editor. The second and third values are the count values (the number the card represents, used for counting) and face values (characters). Model your real deck after this one and check for yourself!
I’m sure many of those who read this thread have heard of Pontifex, or the Solitaire cipher. This is my attempt to implement a general form of that algorithm which can accept as face values any type of data, including more decks. This python module even allows for a deck of decks! As written, it is meant to operate just like the card algorithm, so if you wanted to you could print up code books of what your ‘field agents’ are carrying decks of cards to generate! This module also has two password generating routines, one which uses the solitaire deck simply, and another that is a play on the deck of decks idea.
Here is v. 0.0.3 of my writing of this algorithm. This is not neat and pretty, merely functional. The first block of code is solitaire.py. It executes when called on the console (only tested on UNIX-like systems) and must be passed arguments to work. There is a class and list of functions in solitaire.py. Deck class handles all the stuff you’d expect a deck in solitaire to handle: pushing cards, popping cards, getting characters, advancing state, and a built-in make. The functions in solitaire.py are mainly for loading and unloading deck states and to operate the command-line form.
Advpass option for command line operation is a demonstration of nested decks, basically a deck of decks. The deck class is flexible enough to take characters, strings, binary blobs, functions, or anything else that counts as an object as a card’s representation.
I wrote pyrand.py to interface to /dev/urandom and serve me up tasty 32-bit unsigned random integers. Replace in code with your own solution as I suspect pyrand is the slow spot in the shuffle routines in solitaire.py.
I decided to write this because I wanted to start writing python code where I implement quantum computing proof cryptographic algorithms and protocols. I think OpenPGP is sorely lacking in post-quantum computing foresight at this point and warez has to get out there to handle this threat.
Yea yea, I know it’s sloppy code. I wrote it to work, and I may work on cleaning it up and making it faster and more general. In the event I don’t, here’s a little present for y’all:
This is the first time this code has left this system, consider it licensed under BSD by:
Daniel Duffield
LucianSolaris@gmail.com
https://www.facebook.com/LucianSolaris
Output of `./solitaire.py –help`:
solitaire.py:
pyrand.py: