From bcb347a8d967eebca41cf526334f1099d7db47b8 Mon Sep 17 00:00:00 2001 From: KKlochko Date: Sat, 28 Oct 2023 17:16:04 +0300 Subject: [PATCH] Add a function to encrypt a message with the gamma cipher. --- src/cipher_analytical_machine/ciphers/gamma.clj | 16 +++++++++++++++- .../ciphers/gamma_test.clj | 7 +++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/cipher_analytical_machine/ciphers/gamma.clj b/src/cipher_analytical_machine/ciphers/gamma.clj index c6c0e76..1e5c422 100644 --- a/src/cipher_analytical_machine/ciphers/gamma.clj +++ b/src/cipher_analytical_machine/ciphers/gamma.clj @@ -1,5 +1,8 @@ (ns cipher-analytical-machine.ciphers.gamma - (:require [clojure.string :as cs]) + (:require + [clojure.set :as set] + [clojure.string :as cs] + [cipher-analytical-machine.ciphers.simple-substitution :as ss]) (:gen-class)) (defn add-mod @@ -40,6 +43,17 @@ (map vector array) (map (fn [[a g]] (add-mod a g module)))))) +(defn encrypt-message + "Encrypt a message using the gamma cipher. The function is case-insensitive. The key is an array of three elements [a b c]. The array contains integer in range [0, module)." + [key symbols message] + (let [module (count symbols) + table (ss/generate-sorted-substitution-table symbols)] + (->> message + (ss/decrypt-by-table (set/map-invert table)) + (encrypt-array key module) + (ss/decrypt-by-table table) + (cs/join)))) + (defn decrypt-array "Decrypt an array using the gamma cipher. The function is case-insensitive. The key is an array of three elements [a b c]. The array contains integer in range [0, module)." [key module array] diff --git a/test/cipher_analytical_machine/ciphers/gamma_test.clj b/test/cipher_analytical_machine/ciphers/gamma_test.clj index f12757c..e9975bc 100644 --- a/test/cipher_analytical_machine/ciphers/gamma_test.clj +++ b/test/cipher_analytical_machine/ciphers/gamma_test.clj @@ -39,6 +39,13 @@ [4 32 15] 33 [3 14 1 4 18 19 23 8 27 17] [6 28 2 8 3 5 13 16 21 1] [1 2 3 ] 3 [0 2 1 1 0 1 2 2 0] [0 1 2 2 0 2 1 1 0]))) +(deftest encrypt-message-test + (testing "Checking that the message is encrypted as expected" + (are [key symbols message expected] + (= expected (encrypt-message key symbols message)) + [4 32 15] "абвгґдеєжзиіїйклмнопрстуфхцчшщьюя" "гкбґопужчн" "ешвжгдймсб" + [1 2 3 ] "абв" "авббабвва" "абввавбба"))) + (deftest decrypt-array-test (testing "Checking that the message is decrypted as expected." (are [key module array expected]