Add a implementation of Caesar cipher.

This commit is contained in:
2023-09-09 21:26:38 +03:00
parent a7a715b942
commit f32ae4a9d3
3 changed files with 101 additions and 3 deletions
+37
View File
@@ -0,0 +1,37 @@
(ns cipher-analytical-machine.caesar
(:require [clojure.string :as cs])
(:gen-class))
(defn calculate-char-index
"Calculate the index of a char."
[char symbols]
(cs/index-of symbols char))
(defn encrypt-index
"Calculates new index of a character. Uses its index, the key and max-index (exclusive)."
[index key max-index]
(-> index
(+ key)
(mod 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))))
(defn encrypt-message
"Encrypt a message using the Caesar cipher."
[message key symbols]
(let [max-index (count symbols)]
(cs/join
(map (fn [char] (encrypt-char char key symbols max-index))
message))))
(defn decrypt-message
"Decrypt the ciphtext using the Caesar cipher."
[ciphertext key symbols]
(encrypt-message ciphertext (- key) symbols))