Files
cipher-analytical-machine/src/cipher_analytical_machine/caesar.clj
T

38 lines
1.0 KiB
Clojure

(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))