Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7ccad8e1e | ||
|
|
79e2957402 |
@@ -0,0 +1,34 @@
|
|||||||
|
(ns cipher-analytical-machine.caesar-analyzers
|
||||||
|
(:require [cipher-analytical-machine.caesar :as caesar]
|
||||||
|
[cipher-analytical-machine.cipher_analyzers :as ca])
|
||||||
|
(:gen-class))
|
||||||
|
|
||||||
|
(defn get-all-texts
|
||||||
|
"Return a list of pairs which have a key and a second posible plaintext."
|
||||||
|
[ciphertext symbols]
|
||||||
|
(let [keys (range (count symbols))]
|
||||||
|
(reduce
|
||||||
|
(fn [acc key]
|
||||||
|
(conj acc [key (caesar/decrypt-message ciphertext key symbols)]))
|
||||||
|
'() keys)))
|
||||||
|
|
||||||
|
(defn get-key
|
||||||
|
"To find the key with frequencies of letters."
|
||||||
|
[ciphertext symbols letter-frequences]
|
||||||
|
(->> (get-all-texts ciphertext symbols)
|
||||||
|
(map (fn [[key text]]
|
||||||
|
[key (ca/chi-squared-statistic text letter-frequences)]))
|
||||||
|
(reduce
|
||||||
|
(fn [[key value] [new-key new-value]]
|
||||||
|
(if (> value new-value) [new-key new-value]
|
||||||
|
[key value]))
|
||||||
|
[0 Double/MAX_VALUE])
|
||||||
|
(first)))
|
||||||
|
|
||||||
|
(defn get-plaintext
|
||||||
|
"Return the plaintext from a ciphertext."
|
||||||
|
[ciphertext symbols letter-frequences]
|
||||||
|
(caesar/decrypt-message ciphertext
|
||||||
|
(get-key ciphertext symbols letter-frequences)
|
||||||
|
symbols))
|
||||||
|
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
(ns cipher-analytical-machine.cipher_analyzers
|
||||||
|
(:require [clojure.string :as cs])
|
||||||
|
(:gen-class))
|
||||||
|
|
||||||
|
(defn count-characters
|
||||||
|
"Count the letters and return map."
|
||||||
|
[text]
|
||||||
|
(reduce
|
||||||
|
(fn [acc val]
|
||||||
|
(assoc acc val
|
||||||
|
(inc (get acc val 0))))
|
||||||
|
{} text))
|
||||||
|
|
||||||
|
(defn chi-squared-letter-statistic
|
||||||
|
"To calculate the frequency distribution of a letter."
|
||||||
|
[letter-count letter-frequence length-text]
|
||||||
|
(let [letter-frequence (* length-text letter-frequence)]
|
||||||
|
(/ (Math/pow
|
||||||
|
(- letter-count letter-frequence) 2)
|
||||||
|
letter-frequence)))
|
||||||
|
|
||||||
|
(defn chi-squared-statistic
|
||||||
|
"To calculate the frequency distribution of a language. More detail about the algorithm here: http://practicalcryptography.com/cryptanalysis/text-characterisation/chi-squared-statistic/"
|
||||||
|
[text letter-frequences]
|
||||||
|
(let [length-text (count text)
|
||||||
|
letter-counts (count-characters (cs/lower-case text))]
|
||||||
|
;letter-counts
|
||||||
|
(reduce
|
||||||
|
(fn [acc [char count]]
|
||||||
|
(+ acc
|
||||||
|
(if (contains? letter-frequences char)
|
||||||
|
(chi-squared-letter-statistic count
|
||||||
|
(get letter-frequences char)
|
||||||
|
length-text)
|
||||||
|
0)))
|
||||||
|
0
|
||||||
|
letter-counts)))
|
||||||
|
|
||||||
Reference in New Issue
Block a user