Skip to content

Instantly share code, notes, and snippets.

@pgergis
Last active July 10, 2018 22:46
Show Gist options
  • Save pgergis/698ad5f3edca8c781deaf7ef9c5447f0 to your computer and use it in GitHub Desktop.
Save pgergis/698ad5f3edca8c781deaf7ef9c5447f0 to your computer and use it in GitHub Desktop.
Vigenere Cipher Encoding (Haskell)
-- file: vigenereCipher.hs
import Data.Char
let2int :: Char -> Int
let2int c = ord c - ord 'a'
int2let :: Int -> Char
int2let n = chr (ord 'a' + n)
stringToWord :: String -> String
stringToWord s = [c | c <- cs, isLower c] where cs = concat (words (map toLower s))
-- Vigenere cipher takes input string and cycles to create a key.
-- Key/Message pair are then looked up in an alphabet table to find cipher.
-- Math: Ci = (Mi + Ki) mod 26
-- Methodology:
-- 1. concat ! replicate key n times where n is (size of message / size of key) + 1
-- 2. let2int both message and key, add them together by index, and take mod; return cipher
keygen :: String -> String -> String
keygen mes key = concat (replicate n key) where n = (length mes `div` length key) + 1
vEncodeWord :: String -> String -> String
vEncodeWord mes key = [int2let (((let2int m) + (let2int k)) `mod` 26) | (m,k)<-zip mes (keygen mes key)]
vEncodeString :: String -> String -> String
vEncodeString mes key = vEncodeWord m k
where m = stringToWord mes
k = keygen m (stringToWord key)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment