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.

Pages: 1 2

6 Responses to “Solitaire Cipher”

  1. Dave Webb said

    My Python solution:

    def movedown(deck,entry,move):
        """Move a card down a number of cards in the deck"""
        newindex = deck.index(entry) + move
        if newindex >= len(deck):
            newindex -= len(deck) - 1
        deck.remove(entry)
        deck.insert(newindex,entry)
    
    def countcut(deck,count):
        """a counted cut, based on the number of the bottom card in
        the deck, moves the top count cards to just above the bottom
        card"""
        deck[-1:1] = deck[:count]
        del(deck[:count])
    
    def joker(card):
        """Is the card a joker?"""
        return card in ('A','B')
    
    def step(deck):
        """Perform a step on the deck returning the key"""
    
        #  A joker is moved one card down the deck, wrapping around the
        #  end of the deck if necessary
        movedown(deck,'A',1)
        
        # the B joker is moved two cards down the deck, again wrapping
        # around the deck if necessary.
        movedown(deck,'B',2)
    
        # a triple-cut swaps all the cards above the highest joker in the
        # deck with all the cards below the lowest joker in the deck,
        # leaving the two jokers and the cards between them in place.
        indexa = deck.index('A')
        indexb = deck.index('B')
    
        if indexb > indexa:
            topindex, botindex = indexa, indexb
        else:
            topindex, botindex = indexb, indexa
    
        deck.extend(deck[topindex:botindex + 1])
        deck.extend(deck[:topindex])
        del(deck[:botindex + 1])
    
        # Fourth, a counted cut, based on the number of the bottom card in
        # the deck. the cards are numbered 1 to 52 in bridge order with
        # ace low to king high in each suit, clubs, diamonds, hearts,
        # spades, and either joker counting as 53
        count = deck[-1]
        
        if joker(count):
            count = 53
        
        countcut(deck,count)
    
        # Then look at the top card in the deck and count down the given
        # number to determine the current key card.
        count = deck[0]
        
        if joker(count):
            count = 53
        
        return deck[count]
    
    def keydeck(deck,key):
        # For each character in the key, perform a single step then do a
        # counted cut on the number of the current character, with
        # A=1...Z=26
        for count in [ord(c) - 64 for c in key.upper()]:
            step(deck)
            countcut(deck,count)
    
    def solitare(plaintext,key="",decrypt=False):
        """encrypt and decrypt using the solitare cyper"""
    
        # Make uppercase and remove spaces
        plaintext = plaintext.upper().replace(' ','')
    
        # The plain-text has nulls (the letter X) added to the end to make
        # the message length a multiple of five
        pad = 5 - len(plaintext) % 5
        if pad != 5:
            plaintext += 'X'
    
        # Create a deck in bridge order
        deck = range(1,53) + ['A','B']
        keydeck(deck,key)
     
        ciphertext = ''
        count = 0
    
        for c in plaintext:
            # the cipher-text is split into five-character blocks for
            # convenience.
            if count == 5:
                ciphertext += ' '
                count = 0
    
            key = step(deck)
    
            # the jokers are skipped
            while joker(key):
                key = step(deck)
            
            # each character is added (for encryption) or subtracted (for
            # decryption) from the current text character, wrapping around
            # the alphabet as necessary
            e = ord(c)
    
            if (decrypt):
                e -= key
                while e < ord('A'):
                    e += 26
            else:
                e += key
                while e > ord('Z'):
                    e -= 26
                count += 1
    
            ciphertext += chr(e)
    
        return ciphertext
    
    print solitare("AAAAAAAAAA")
    print solitare("AAAAAAAAAAAAAAA","FOO")
    print solitare("SOLITAIRE","CRYPTONOMICON")
    
    print solitare("EXKYI ZSGEH",decrypt=True)
    print solitare("ITHZU JIWGR FARMW","FOO",decrypt=True)
    print solitare("KIRAK SFJAN","CRYPTONOMICON",decrypt=True)
    
  2. Dave Webb said

    Line 84 should be:

    plaintext += 'X' * pad
    

    and not:

    plaintext += 'X'
    
  3. Mike said

    My python version.

    
    from itertools import chain, ifilter, imap, izip
    
    A = 53
    B = 54
    N_CARDS = 54
    ORD_A = ord('A')
    
    class Deck(list):
        def __init__(self, key=''):
            list.__init__(self, range(1,55))
    
            self.step()
            for ch in key:
                self.counted_cut(ord(ch) - ORD_A + 1)
                self.step()
    
        def move(self, card, distance):
            fm = self.index(card)
            to = fm + distance
            if to >= N_CARDS:
                to -= (N_CARDS-1)
    
            self.insert(to, self.pop(fm))
    
        def triple_cut(self):
            a = self.index(A)
            b = self.index(B)
            s, e = (a, b+1) if a < b else (b, a+1)
            self[:] = self[e:] + self[s:e] + self[:s]
    
        def counted_cut(self, count):
            self[:] = self[count:-1] + self[:count] + self[-1:]
    
        def step(self):
            self.move(A, 1)
            self.move(B, 2)
            self.triple_cut()
            self.counted_cut(min(self[-1], A))
    
        def __iter__(self):
            while True:
                ndx = min(self[0], A)
    
                if self[ndx] < A:
                    yield self[ndx]
                        
                self.step()
    
    
    def encrypt(text, key=''):
        encode = lambda c,k: chr((ord(c) - ORD_A + k)%26 + ORD_A)
            
        padded_text = chain(text, ['X']*(-len(text)%5))
        
        cyphertext =  imap(encode, padded_text, Deck(key))
        
        groups = imap(''.join, izip(*[cyphertext]*5))
        
        return ' '.join(groups)
    
    
    def decrypt(text, key=''):
        decode = lambda c,k: chr((ord(c) - ORD_A - k)%26 + ORD_A)
    
        letters = (c for c in text if c.isupper())
    
        return ''.join(imap(decode, letters, Deck(key)))
    
    
  4. Veer said

    My attempt in scheme.

    (define (joker? n) (or (= n joker1) (= n joker2)))
    (define joker1 53)
    (define joker2 54)
    
    ;utils
    (define (find-elem i v pred?)
      (cond
        [(= i (vector-length v)) (error 'oops)]
        [(pred? (vector-ref v i)) i]
        [else (find-elem (+ i 1) v pred?)]))
    
    (define (string->nums s)
      (let ([l (string->list (string-upcase s))])
        (map (lambda (c) (mod (mod (char->integer c) 64) 26)) l)))
    
    (define (nums->string nl)
      (map (lambda (n)
             (if (= 0 n) #\Z (integer->char (+ n 64)))) nl))
    
    
    ;start
    (define (shift v index end op)
      (let ([val (vector-ref v index)])
        (let loop ([index index])
          (cond
            [(= index end) (vector-set! v index val)]
            [else (vector-set! v index (vector-ref v (op index 1))) 
                  (loop (op index 1))]))))
    
    (define (mov v i n )
      (let ([index (mod i (vector-length v))])
        (let ([end-index (mod (+ index n) (vector-length v))])
          (if (<= index end-index)
              (shift v index end-index +)
              (shift v index (+ 1 end-index) -)))))
    
    (define (count-cut v n ei)
      (let ([si (- n 1)]) 
        (let loop ([si si] [ei ei])
          (cond
            [(< si 0) v]
            [(zero? si) (shift v si ei +)]
            [else (shift v si ei +)
                  (loop (- si 1) (- ei 1))]))))
    
    (define (triple-cut v)
      (let ([joker1 (find-elem 0 v joker?)])        
        (count-cut v joker1 (- (vector-length v) 1))
          (let ([joker2 (find-elem 1 v joker?)])
            (count-cut v (+ joker2 1) (- (vector-length v) (+ 1 joker1)))
            v)))
    
    (define (move-jokers deck)
      (mov deck (find-elem 0 deck (lambda (n) (= n joker1))) 1)
      (mov deck (find-elem 0 deck (lambda (n) (= n joker2))) 2))
    
    (define (steps deck)
      (move-jokers deck)
      (triple-cut deck)
      (let ([last-num (vector-ref deck (- (vector-length deck) 1))])
        (count-cut deck (min 53 last-num) (- (vector-length deck) 2))))
    
    (define (key-deck key deck)
      (for-each (lambda (i)
                  (steps deck)
                  (count-cut deck i (- (vector-length deck) 2)))
                key))
    
    (define (enc-dec msg key op)
    
      (define (get-next deck)
        (steps deck)
        (let ([n (vector-ref deck (min 53 (vector-ref deck 0)))])
          (if (>= n 53) (get-next deck) n)))
      
      (let ([msg (string->nums msg)]
            [key (string->nums key)]
            [deck (build-vector 54 (lambda (i) (+ i 1)))])
        (key-deck key deck)
        
        (list->string
         (nums->string (map (lambda (m) (mod (op m (get-next deck)) 26)) msg)))))
            
    (define (enc msg key)
      (enc-dec msg key +))
    
    (define (dec msg key)
      (enc-dec msg key -))
      
    
    (define (test)
      (and
       (equal? (enc "AAAAAAAAAA" "" ) "EXKYIZSGEH")
       (equal? (enc "AAAAAAAAAAAAAAA" "FOO" ) "ITHZUJIWGRFARMW")
       (equal? (enc "SOLITAIRE" "CRYPTONOMICON" ) "KIRAKSFJA")
       
       (equal? (dec "EXKYIZSGEH" "") "AAAAAAAAAA")
       (equal? (dec "ITHZUJIWGRFARMW" "FOO") "AAAAAAAAAAAAAAA")
       (equal? (dec "KIRAKSFJA" "CRYPTONOMICON")  "SOLITAIRE")))
    
    
  5. Veer said

    Another attempt using pattern matching.

    (define DECK (build-list 54 (lambda (i) (+ i 1))))
    (define joker1 53)
    (define joker2 54)
    (define (joker? j) (or (equal? j joker1) (equal? j joker2)))
    
    (define (to-num c)
      (modulo
       (- (char->integer (char-upcase c)) 64) 26))
    
    (define (to-char n)
      (let ([n (modulo n 26)])
        (if (zero? n) #\Z (integer->char (+ n 64)))))
    
    (define (eq=? val1)
      (lambda (val2)
        (= val1 val2)))
    
    (define (move-joker v joker)
      (match v
        [(list a x ... (? (eq=? joker)) ) (append (list a joker) x)]
        [(list x ... (? (eq=? joker)) b y ...) (append x (list b joker) y)]))
    
    (define (move-jokers v)
      (move-joker (move-joker (move-joker v joker1) joker2) joker2))
    
    (define (triple-cut v)
      (match v
        [(list x ... (? joker? j1) y ... (? joker? j2) z ... ) (append z (list j1) y (list j2) x)]))
    
    (define (cut v n)
      (let ([val (list-ref v (- n 1))])
        (match v
          [(list x ... (? (eq=? val) b) z ... c) (append z x (list b c))])))
            
    (define (step v)
      (let ([v (triple-cut (move-jokers v))])
        (cut v (min 53 (list-ref v (- (length v) 1))))))
    
    (define (key-deck v key)
      (match key
        [(list ) v]
        [(list a b ...) (key-deck (cut (step v) (to-num a)) b) ]))
                
    (define (enc-dec msg deck op)
      (let ([deck (step deck)])
        (let ([n (list-ref deck (min 53 (first deck)))])
            (cond
              [(empty? msg) empty]
              [(joker? n) (enc-dec msg deck op)]
              [else (cons (to-char (op (to-num (first msg)) n))
                          (enc-dec (rest msg) deck op))]))))
    
    (define (enc msg key)
      (let ([deck (key-deck DECK (string->list key))])
        (list->string (enc-dec (string->list msg) deck +))))
    
    (define (dec msg key)
      (let ([deck (key-deck DECK (string->list key))])
        (list->string (enc-dec (string->list msg) deck -))))
    

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 196 other followers