Creation
March 3, 2009
We first save the cipher-text as a string:
(define cipher-text
(list->string (map integer->char
'(14 11 78 17 27 12 ... 4 26 12 28 7 93))))
Since we know the password is fixed and has length n, we know that every nth character in the plain-text has been enciphered with the same character of the password. Thus, our strategy is to break down the cipher-text into n stripes, assume that the most frequently-occurring character in each stripe represents the space character, and use xor to find the password character for that stripe. We try various n in turn until one works, giving us sensible English-language text.
(define (try-pass n text)
(let loop ((i 0) (pwd '()))
(if (= i n)
(list->string (reverse pwd))
(loop (+ i 1) (cons (char-xor #\space
(caar (freq (extract n i text)))) pwd)))))
Try-pass
uses extract to get a stripe, freq
to find the most common character, and char-xor
to perform the xor operation:
(define (char-xor a b)
(define (xor a b)
(cond ((eq? a b) 0)
((zero? a) b)
((zero? b) a)
(else (+ (if (eq? (even? a) (even? b)) 0 1)
(* (xor (quotient a 2) (quotient b 2)) 2)))))
(integer->char (xor (char->integer a) (char->integer b))))
(define (extract span mod text)
(let loop ((i 0) (ts '()))
(cond ((= (string-length text) i)
(list->string (reverse ts)))
((= (modulo i span) mod)
(let ((t (string-ref text i)))
(loop (+ i 1) (cons t ts))))
(else (loop (+ i 1) ts)))))
(define (freq text)
(if (string=? "" text) '()
(let ((txt (sort charlist text))))
(let loop ((txt (cdr txt)) (prev (car txt)) (cnt 1) (freqs '()))
(cond ((null? txt)
(sort (lambda (x y) (> (cdr x) (cdr y)))
(cons (cons prev cnt) freqs)))
((char=? (car txt) prev)
(loop (cdr txt) prev (+ cnt 1) freqs))
(else (loop (cdr txt) (car txt) 1
(cons (cons prev cnt) freqs))))))))
All that’s left is to apply the password to the cipher-text to read the plain-text:
(define (crypt password text)
(define (cycle xs) (set-cdr! (last-pair xs) xs) xs)
(let loop ((pwd (cycle (string->list password))) (txt (string->list text)) (out '()))
(if (null? txt) (list->string (reverse out))
(loop (cdr pwd) (cdr txt) (cons (char-xor (car pwd) (car txt)) out)))))
We try several password lengths, in turn:
> (try-pass 1 cipher-text)
"e"
> (try-pass 2 cipher-text)
"ee"
> (try-pass 3 cipher-text)
"ess"
> (try-pass 4 cipher-text)
"see "
> (try-pass 5 cipher-text)
"seees"
> (try-pass 6 cipher-text)
"eseess"
> (try-pass 7 cipher-text)
"Genesis"
And that works. The password is “Genesis” and the plain-text is the story of Creation from the beginning of the Holy Bible:
> (crypt "Genesis" cipher-text)
"In the beginning ... creation."
Note that the same procedure that performs encryption also performs decryption, since xor is a reflexive operator; thus the cipher-text was created like this:
> (define cipher-text (crypt "Genesis" plain-text))
The decryption program is available at http://programmingpraxis.codepad.org/N8fi45eN.
Can’t believe nobody else commented on this… That one was a lot of fun!
I took a different approach from the proposed Scheme solution, went for a dictionary attack:
Basically, I start by building an attack dictionary, sorted by length. Then I brute-force my way through this attack dictionary, trying to decrypt the beginning of the encrypted text using each one of the possible passwords, and I count the number of real words I can find in the decrypted version.
Of course it could probably be automated completely by simply returning the password yielding the highest number of real words, but it works for me like that. Running it as it is shown here (scanning the first 50 letters of the encrypted text, and trying passwords up to 8 letters long), it shows me the list of following possible keys (only showing the keys producing 6 or more known words):
6 matches found with imber
6 matches found with infer
6 matches found with inker
6 matches found with ceresin
6 matches found with chooser
6 matches found with geronto
6 matches found with oenolin
6 matches found with Allower
6 matches found with Ceresin
6 matches found with Chooser
6 matches found with Foresin
8 matches found with Genesis
6 matches found with Geronto
6 matches found with Getaway
6 matches found with Subjoin
6 matches found with Thrower
6 matches found with Vetiver
I followed the ideas of the solution here, but wished to automate the process
a bit more. I had my code try different passwords (given by assuming that space
is the most common character), checking those words against membership in my
system’s dict file. It outputs all possibilities, so it still requires a human
eye to sort through the gobbledygook.
If you are really interested in automating this program fully, Google for ‘Kasiski examination’ and go from there. Like a lot of these things, it’s named for the wrong man; Charles Babbage figured it out twenty years before Kasiski.
Interesting stuff! It’s reminiscent of some of Simon Singh’s “The Code Book,” a decent source and fun read.
Like others I want to automate the process as much as possible.
So my slightly different implementation returns a password and a “confidence number” based on the frequencies of “” and “e”.
Then we can search for all passwords given a maximum length and a confidence threshold.
Clojure code:
For example, we can search for all passwords less than 20 chars with at least 80% confidence:
This one is funny:
[…] In their book Software Tools, Brian Kernighan and P. J. Plauger describe a simple command for encrypting files. It works by xor-ing each byte of a file with a byte of the key, extending the key cyclically until it is the same length as the text. The xor operation is symmetric, so only one program is needed to perform both encryption and decryption. This isn’t a particularly secure encryption algorithm; we showed how to break it in one of our earliest exercises. […]
I had the similar ideas with Graham, and I improve my script when I saw Graham’s since I am not familiar with Python.
from collections import Counter
import string
def crack(text, n):
pwd = []
for seq in [text[i::n] for i in xrange(n)]:
p = chr(ord(‘ ‘) ^ int(Counter(seq).most_common(1)[0][0]))
if is_pwd_char(p):
pwd.append(p)
else:
return None
return pwd
def is_pwd_char(ch):
return ch in string.digits or ch in string.ascii_letters
def decrypt(text, pwd):
return [chr(ord(pwd[i % len(pwd)]) ^ int(x)) for (i, x) in enumerate(text)]
if __name__ == ‘__main__’:
with open(‘/tmp/cipher-text’) as f:
text = f.read().split()
for i in range(1, 21):
pwd = crack(text, i)
if pwd != None:
print ‘decrypt with pwd: %s’ % pwd
print ”.join(decrypt(text, pwd))
https://github.com/ftt/programming-praxis/blob/master/20090303-creation/creation.py