Skip to content

Instantly share code, notes, and snippets.

@egri-nagy
Created October 24, 2017 05:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save egri-nagy/1c18e7d297ac522b61d209a22ab50fea to your computer and use it in GitHub Desktop.
Save egri-nagy/1c18e7d297ac522b61d209a22ab50fea to your computer and use it in GitHub Desktop.
Caesar shift cipher
;; Caesar shift and its brute-force attack.
(def letters "abcdefghijklmnopqrstuvwxyz ")
(defn shift-map
"A hash-map that maps letters to letters cyclically shifted by n."
[n]
(zipmap letters
(take (count letters)
(drop n (cycle letters)))))
(defn encrypter
"Returns a function that encrypts plaintext by an n-shift cipher."
[n]
(fn [text]
(apply str
(map (shift-map n) text))))
(defn decrypter
"A decrypter is just an encrypter that shifts backwards."
[n]
(encrypter (mod (- n) (count letters))))
(defn brute-force-attack
"Calculates all shifts and thus breaking the cipher."
[ciphertext]
(map
(fn [n] ((decrypter n) ciphertext))
(range 1 (count letters))))
;; STUDENT CHALLENGE: "jyvqijkuvdjqmyeqwzhijqiroiqszdxeqrbekuqmzbbqxvjqrdqvnjhrqfezdjqzdqwzdrbqxhruv"
;; DECIPHER THIS: "pazv tmonpxmfamiurdrmkagmefndfrqmvem afmfurmenzrmnem rhrdmyrnhv t"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment