This repository was archived by the owner on Oct 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCipher.hs
58 lines (49 loc) · 1.5 KB
/
Cipher.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
module Cipher where
import qualified Data.Char as Char
import qualified Data.List as List
toLowerList :: [Char] -> [Char]
toLowerList = map Char.toLower
-- >>> (caesarShift 2 'a', caesarShift (-2) 'a')
-- ('c','y')
caesarShift :: Int -> Char -> Char
caesarShift n chr
| isAlpha = Char.chr neword
| otherwise = chr
where
ord = Char.ord . Char.toLower $ chr
shift = rem (ord - 97 + n) 26
neword = if shift >= 0
then 97 + shift
else 97 + 26 + shift
isAlpha = Char.isAscii chr && Char.isAlpha chr
-- >>> x = toCaesar "hello world" 1000000
-- >>> y = fromCaesar x 1000000
-- >>> (x , y)
-- ("VSZZC KCFZR","hello world")
toCaesar :: String -> Int -> String
toCaesar txt shift =
map (Char.toUpper . caesarShift shift) txt
fromCaesar :: String -> Int -> String
fromCaesar txt shift =
map (caesarShift $ shift * (-1)) txt
-- >>> x = toVigenere' "attackatdawn" "lemon"
-- >>> y = fromVigenere x "lemon"
-- >>> (x,y)
-- ("LXFOPVEFRNHR","attackatdawn")
--
toVigenere :: String -> String -> String
toVigenere txt key =
zipWith f txt' $ List.cycle key'
where
txt' = toLowerList txt
key' = cycle . toLowerList $ key
f a b =
Char.toUpper $ caesarShift (Char.ord b - 97) a
fromVigenere :: String -> String -> String
fromVigenere cipher key =
zipWith f cipher' key'
where cipher' = toLowerList cipher
key' = cycle . toLowerList $ key
f a b = caesarUnshift (Char.ord b) a
caesarUnshift a b =
caesarShift ((-1) * (a - 97)) b