Compare commits

...
7 Commits
Author SHA1 Message Date
KKlochko 4607f7f013 Update Caesar Analyzers to be case-insensitive and testable.
continuous-integration/drone/push Build is passing
2023-09-22 21:04:11 +03:00
KKlochko 79e316c51b Update the Caesar to be case-insensitive and skip unknown symbols.
continuous-integration/drone/push Build is passing
2023-09-21 21:05:22 +03:00
KKlochko 20c1d1ef1b Update symbol defaults, factories to have only lower alphabets.
continuous-integration/drone/push Build is passing
2023-09-21 21:01:52 +03:00
KKlochko 6833ade696 Add the language option for symbols. 2023-09-21 20:57:25 +03:00
KKlochko 9e4c46814c Update the CLI to have separated actions and an option initializer. 2023-09-21 20:55:43 +03:00
KKlochko 6f15eedacd Add tests for the cipher-analyzers module.
continuous-integration/drone/push Build is passing
2023-09-18 22:01:02 +03:00
KKlochko 182d9894f7 Rename the cipher_analyzer module to cipher-analyzer. 2023-09-18 21:57:32 +03:00
9 changed files with 228 additions and 84 deletions
+15 -8
View File
@@ -14,21 +14,28 @@
(+ key)
(mod max-index)))
(defn encrypt-or-skip
"If symbols do not have a character, then it will be skipped."
[index character key symbols max-index]
(if (nil? index) character
(get symbols
(encrypt-index index key max-index))))
(defn encrypt-char
"Calculates new index of a character. Uses a char from symbols, the key and max-index (exclusive)."
[char key symbols max-index]
(get symbols
(-> char
(calculate-char-index symbols)
(encrypt-index key max-index))))
(-> char
(calculate-char-index symbols)
(encrypt-or-skip char key symbols max-index)))
(defn encrypt-message
"Encrypt a message using the Caesar cipher."
"Encrypt a message using the Caesar cipher. The function is case-insensitive."
[message key symbols]
(let [max-index (count symbols)]
(cs/join
(map (fn [char] (encrypt-char char key symbols max-index))
message))))
(->> message
(cs/lower-case)
(map (fn [char] (encrypt-char char key symbols max-index)))
(cs/join))))
(defn decrypt-message
"Decrypt the ciphtext using the Caesar cipher."
@@ -1,6 +1,7 @@
(ns cipher-analytical-machine.caesar-analyzers
(:require [cipher-analytical-machine.caesar :as caesar]
[cipher-analytical-machine.cipher_analyzers :as ca])
[clojure.string :as cs]
[cipher-analytical-machine.cipher-analyzers :as ca])
(:gen-class))
(defn get-all-texts
@@ -12,23 +13,36 @@
(conj acc [key (caesar/decrypt-message ciphertext key symbols)]))
'() keys)))
(defn get-all-scores
"For pairs (key, plaintext) finds scores and return list of pairs [key, score]."
[letter-frequences pairs]
(map (fn [[key text]]
[key (ca/chi-squared-statistic text letter-frequences)])
pairs))
(defn get-min-score-pair
"For pairs (key, plaintext) finds scores and return list of pairs [key, score]."
[pairs]
(reduce
(fn [[key value] [new-key new-value]]
(if (> value new-value) [new-key new-value]
[key value]))
[0 Double/MAX_VALUE]
pairs))
(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])
(get-all-scores letter-frequences)
(get-min-score-pair)
(first)))
(defn get-plaintext
"Return the plaintext from a ciphertext."
"Return the plaintext from a ciphertext. The function is case-insensitive."
[ciphertext symbols letter-frequences]
(caesar/decrypt-message ciphertext
(get-key ciphertext symbols letter-frequences)
symbols))
(let [ciphertext (cs/lower-case ciphertext)]
(caesar/decrypt-message ciphertext
(get-key ciphertext symbols letter-frequences)
symbols)))
@@ -1,4 +1,4 @@
(ns cipher-analytical-machine.cipher_analyzers
(ns cipher-analytical-machine.cipher-analyzers
(:require [clojure.string :as cs])
(:gen-class))
+66 -18
View File
@@ -12,6 +12,9 @@
(def cipher-options
#{"Caesar"})
(def language-options
#{"en", "uk"})
(def cli-options
[["-m" "--message MESSAGE" "The message will be encrypted or decrypted."]
["-M" "--message-file MESSAGE-FILE" "The file contains the message that will be encrypted or decrypted."]
@@ -22,6 +25,8 @@
["-d" "--decrypt" "Decrypt the message."]
["-s" "--symbols" "The string will be used as a set of symbols for a cipher."
:default (sf/default-symbol-factory "en")]
["-l" "--language CODE" "The string will be used to set a default symbols for a cipher."
:validate [#(contains? language-options %) "Must be a code from the list: en, uk!!!"]]
["-C" "--cracking" "Cracking the encrypted message."]
["-h" "--help"]])
@@ -88,29 +93,72 @@
(println exit-message)
(System/exit (if status 0 1)))
(defn get-message
"Return the message"
[options arguments]
(cond
(contains? options :message)
(:message options)
(defn get-or-load-option
"Return the option value or load the value from a file."
[options arguments option]
(let [file-option (keyword (str (name option) "-file"))]
(cond
(contains? options option)
(option options)
(contains? options :message-file)
(file/read-file (:message-file options))))
(contains? options file-option)
(file/read-file (file-option options)))))
(defn set-option
"Set a option in the option map."
[options option value]
(-> options
(assoc option value)))
(defn set-symbols
"Set defaults symbols for a language."
[options]
(set-option options :symbols
(sf/default-symbol-factory (:language options))))
(defn load-and-set-option
"Load the option and set it."
[options option]
(->> (get-or-load-option options nil option)
(set-option options option)))
(defn load-all-options
"Load all options."
[options]
(-> options
(set-symbols)
(load-and-set-option :message)))
(defn cracking-actions
[options arguments action-type]
(let [message (:message options)
symbols (:symbols options)
frequencies symbol-frequences/english-letter-frequences]
(cond
(= action-type :cracking)
(caesar-analyzers/get-plaintext message symbols frequencies)
)))
(defn crypt-actions
[options arguments action-type]
(let [message (:message options)
key (Integer/parseInt (:key options))
symbols (:symbols options)]
(cond
(= action-type :encrypt)
(caesar/encrypt-message message key symbols)
(= action-type :decrypt)
(caesar/decrypt-message message key symbols))))
(defn actions
[options arguments action-type]
(let [message (get-message options arguments)
key (Integer/parseInt (:key options))
symbols (:symbols options)]
(let [options (load-all-options options)]
(println
(cond
(contains? #{:encrypt :decrypt} action-type)
(crypt-actions options arguments action-type)
(= action-type :cracking)
(caesar-analyzers/get-plaintext message symbols symbol-frequences/english-letter-frequences)
(= action-type :encrypt)
(caesar/encrypt-message message key symbols)
(= action-type :decrypt)
(caesar/decrypt-message message key symbols)))))
(cracking-actions options arguments action-type)))))
@@ -2,7 +2,7 @@
(:require [clojure.string :as cs])
(:gen-class))
(defn lower-english-alphabet-factory
(defn english-alphabet-factory
"Return the English alphabet with only lowercase letters"
[]
(reduce
@@ -10,23 +10,11 @@
""
(range (int \a) (inc (int \z)))))
(defn english-alphabet-factory
"Return the English alphabet with lower and upper case letters"
[]
(let [letters (lower-english-alphabet-factory)]
(str letters (cs/upper-case letters))))
(defn lower-ukrainian-alphabet-factory
(defn ukrainian-alphabet-factory
"Return the Ukrainian alphabet with only lowercase letters"
[]
"абвгґдеєжзиіїйклмнопрстуфхцчшщьюя")
(defn ukrainian-alphabet-factory
"Return the Ukrainian alphabet with lower and upper case letters"
[]
(let [letters (lower-ukrainian-alphabet-factory)]
(str letters (cs/upper-case letters))))
(defn digit-set-factory
"Return digits"
[]
@@ -48,14 +36,10 @@
(cond
(= language-code "en")
(str (english-alphabet-factory)
(punctuation-symbol-factory)
(digit-set-factory)
\ )
(= language-code "uk")
(str (ukrainian-alphabet-factory)
(punctuation-symbol-factory)
(digit-set-factory)
\ )
:else
@@ -0,0 +1,76 @@
(ns cipher-analytical-machine.caesar-analyzers-test
(:require
[clojure.test :refer :all]
[cipher-analytical-machine.caesar-analyzers :refer :all]
[cipher-analytical-machine.symbol-frequences :as sf]
[cipher-analytical-machine.cipher-analyzers :as ca]
[clojure.string :as cs]))
(deftest get-all-texts-test
(testing "There're three text when the text is 'abc' and the set of symbol is 'abc'."
(is (= 3 (count (get-all-texts "abc" "abc")))))
(testing "A pair must have an integer and a string."
(let [pairs (get-all-texts "abc" "abc")
pair (first pairs)]
(is (and (int? (first pair))
(string? (last pair))))))
(testing "There're 27 combinations for a 'Hello World'."
(let [ciphertext "khoorczruog"
symbols "abcdefghijklmnopqrstuvwxyz "]
(is (= 27 (count (get-all-texts ciphertext symbols)))))))
(deftest get-all-scores-test
(testing "There're 27 combinations for a 'Hello World'."
(let [ciphertext "khoorczruog"
symbols "abcdefghijklmnopqrstuvwxyz "
frequences sf/english-letter-frequences
text-pairs (get-all-texts ciphertext symbols)]
(is (= 27 (count (get-all-scores frequences text-pairs)))))))
(deftest get-min-score-pair-test
(testing "If a key is one, then the min score pair is 15."
(let [scores (list [0 20.0] [1 15.0] [2 30.0])
min-score-pair (get-min-score-pair scores)]
(is (= [1 15.0] min-score-pair)))))
(deftest get-key-test
(let [plaintext "hello world"
ciphertext "khoorczruog"
key 3
symbols "abcdefghijklmnopqrstuvwxyz "
frequences sf/english-letter-frequences]
(testing "The plaintext is encrypted with 3 as the key."
(is (= key (get-key ciphertext symbols frequences)))))
(let [; З поеми "Кавказ" Тараса Григоровича Шевченка:
plaintext "Борітеся – поборете, Вам Бог помагає! За вас правда, за вас слава. І воля святая!"
ciphertext "жхчощйшде–ецхжхчйщй,езєуежхиецхуєиєк!емєезєшецчєзїє,емєезєшештєзє.еоезхтдешздщєд!"
key 7
symbols "абвгґдеєжзиіїйклмнопрстуфхцчшщьюя "
frequences sf/ukrainian-letter-frequences]
(testing "The plaintext is encrypted with 3 as the key."
(is (= key (get-key ciphertext symbols frequences))))))
(deftest get-plaintext-test
(let [plaintext "hello world"
ciphertext "khoorczruog"
symbols "abcdefghijklmnopqrstuvwxyz "
frequences sf/english-letter-frequences]
(testing "The plaintext is encrypted with 3 as the key."
(is (= plaintext (get-plaintext ciphertext symbols frequences))))
(testing "The ciphertext is case-insensitive."
(is (= plaintext (get-plaintext "KhoorcZruog" symbols frequences)))))
(let [; З поеми "Кавказ" Тараса Григоровича Шевченка:
plaintext "Борітеся – поборете, Вам Бог помагає! За вас правда, за вас слава. І воля святая!"
ciphertext "жхчощйшде–ецхжхчйщй,езєуежхиецхуєиєк!емєезєшецчєзїє,емєезєшештєзє.еоезхтдешздщєд!"
key 7
symbols "абвгґдеєжзиіїйклмнопрстуфхцчшщьюя "
frequences sf/ukrainian-letter-frequences]
(testing "The ciphertext is case-insensitive."
(is (= (cs/lower-case plaintext)
(get-plaintext ciphertext symbols frequences))))))
@@ -51,14 +51,20 @@
(testing "The message 'abc' is encrypted to 'bca'"
(is (= "bca" (encrypt-message "abc" 1 symbols))))
(testing "The message 'ABC' is encrypted to 'bca', because of case-insensitive."
(is (= "bca" (encrypt-message "ABC" 1 symbols))))
(testing "The message 'bca' is decrypted to 'abc'"
(is (= "abc" (encrypt-message "bca" -1 symbols))))))
(deftest decrypt-message-text
(let [symbols "abc"]
(testing "The message 'bca' is decrypted to 'abc'"
(is (= "abc" (decrypt-message "bca" 1 symbols)))
(is (= "abc" (decrypt-message "bca" 1 symbols))))
(testing "The message 'BCA' is decrypted to 'abc', because of case-insensitive."
(is (= "abc" (decrypt-message "BCA" 1 symbols))))
(testing "The message 'abc' is encrypted to 'bca'"
(is (= "bca" (decrypt-message "abc" -1 symbols)))))))
(is (= "bca" (decrypt-message "abc" -1 symbols))))))
@@ -0,0 +1,25 @@
(ns cipher-analytical-machine.cipher-analyzers-test
(:require
[clojure.test :refer :all]
[cipher-analytical-machine.cipher-analyzers :refer :all]))
(deftest count-characters-test
(testing "Count two dublicates and one uniq character from a string."
(is (= {\a 2 \b 1}
(count-characters "aba")))))
(deftest chi-squared-letter-statistic-test
(testing "If the frequence of A is 0.1, the text length is 100 and contains 20 times, then the chi-squared is 10."
(is (= 10.0
(chi-squared-letter-statistic 20 0.1 100))))
(testing "If the frequence of A is 0.1, the text length is 10 and contains 5 times, then the chi-squared is 16.0."
(is (= 16.0
(chi-squared-letter-statistic 5 0.1 10)))))
(deftest chi-squared-statistic-test
(let [text "aaaaabbbbb"]
(testing "If the frequences of a and b is 0.1, the text length is 10 and contains them 5 times, then score is 32."
(is (= 32.0
(chi-squared-statistic text {\a 0.1 \b 0.1}))))))
@@ -4,38 +4,22 @@
[cipher-analytical-machine.symbol-factories :refer :all]
))
(deftest lower-english-alphabet-factory-test
(let [symbols (lower-english-alphabet-factory)]
(deftest english-alphabet-factory-test
(let [symbols (english-alphabet-factory)]
(testing "It must have the same order."
(is (= "abcdefghijklmnopqrstuvwxyz" symbols)))
(testing "It must have 26 letters."
(is (= 26 (count symbols))))))
(deftest english-alphabet-factory-test
(let [symbols (english-alphabet-factory)]
(testing "It must have the same order."
(is (= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" symbols)))
(testing "It must have 2*26 letters."
(is (= (* 2 26) (count symbols))))))
(deftest lower-ukrainian-alphabet-factory-test
(let [symbols (lower-ukrainian-alphabet-factory)]
(deftest ukrainian-alphabet-factory-test
(let [symbols (ukrainian-alphabet-factory)]
(testing "It must have the same order."
(is (= "абвгґдеєжзиіїйклмнопрстуфхцчшщьюя" symbols)))
(testing "It must have 33 letters."
(is (= 33 (count symbols))))))
(deftest ukrainian-alphabet-factory-test
(let [symbols (ukrainian-alphabet-factory)]
(testing "It must have the same order."
(is (= "абвгґдеєжзиіїйклмнопрстуфхцчшщьюяАБВГҐДЕЄЖЗИІЇЙКЛМНОПРСТУФХЦЧШЩЬЮЯ" symbols)))
(testing "It must have 2*33 letters."
(is (= (* 2 33) (count symbols))))))
(deftest digit-set-factory-test
(let [symbols (digit-set-factory)]
(testing "It must have the same order."
@@ -61,15 +45,15 @@
(is (= 3 (count symbols))))))
(deftest default-symbol-factory-test
(testing "If language code is 'en', then it must have symbols."
(testing "If language code is 'en', then it must have 27 symbols."
(let [symbols (default-symbol-factory "en")]
(is (= 70 (count symbols)))))
(is (= 27 (count symbols)))))
(testing "If language code is 'uk', then it must have symbols."
(testing "If language code is 'uk', then it must have 34 symbols."
(let [symbols (default-symbol-factory "uk")]
(is (= 84 (count symbols)))))
(is (= 34 (count symbols)))))
(testing "If language code is unidentified, then it must have the 'en'."
(let [symbols (default-symbol-factory "Maybe a code")]
(is (= 70 (count symbols))))))
(is (= 27 (count symbols))))))