How to resolve the algorithm Vigenère cipher step by step in the Clojure programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Vigenère cipher step by step in the Clojure programming language

Table of Contents

Problem Statement

Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.)

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Vigenère cipher step by step in the Clojure programming language

Source code in the clojure programming language

(ns org.rosettacode.clojure.vigenere
  (:require [clojure.string :as string]))

; convert letter to offset from \A
(defn to-num [char] (- (int char) (int \A)))

; convert number to letter, treating it as modulo 26 offset from \A
(defn from-num [num] (char (+ (mod num 26) (int \A))))

; Convert a string to a sequence of just the letters as uppercase chars
(defn to-normalized-seq [str]
  (map #'first (re-seq #"[A-Z]" (string/upper-case str))))
  
; add (op=+) or subtract (op=-) the numerical value of the key letter from the
; text letter.  
(defn crypt1 [op text key] 
  (from-num (apply op (list (to-num text) (to-num key)))))

(defn crypt [op text key]
  (let [xcrypt1 (partial #'crypt1 op)]
    (apply #'str
      (map xcrypt1 (to-normalized-seq text) 
                   (cycle (to-normalized-seq key))))))
   
; encipher a text
(defn encrypt [plaintext key] (crypt #'+ plaintext key))
      
; decipher a text
(defn decrypt [ciphertext key] (crypt #'- ciphertext key))


(ns org.rosettacode.clojure.test-vigenere
  (:require [org.rosettacode.clojure.vigenere :as vigenere]))

(let
 [ plaintext  "Beware the Jabberwock, my son!  The jaws that bite, the claws that catch!"
   key        "Vigenere cipher"
   ciphertext (vigenere/encrypt plaintext  key)
   recovered  (vigenere/decrypt ciphertext key) ]

  (doall (map (fn [[k v]] (printf "%9s: %s\n" k v))
   [ ["Original" plaintext] ["Key" key] ["Encrypted" ciphertext] ["Decrypted" recovered] ])))


  

You may also check:How to resolve the algorithm I before E except after C step by step in the AppleScript programming language
You may also check:How to resolve the algorithm Remove duplicate elements step by step in the EasyLang programming language
You may also check:How to resolve the algorithm Quoting constructs step by step in the Phix programming language
You may also check:How to resolve the algorithm Rosetta Code/Rank languages by popularity step by step in the Wren programming language
You may also check:How to resolve the algorithm Percolation/Mean run density step by step in the EasyLang programming language