Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

XOR cipher #47

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions algorithms/ciphers/Xor.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
module Xor
( encodeB
, decodeB
, encode
, decode
) where

import Data.Char
import Data.Bits

-- Raw encoding function for lists of numbers
-- First argument is the key, second is the data
-- The key will be repeated to the length of the data
encodeB :: Bits a => [a] -> [a] -> [a]
encodeB key = zipWith xor (cycle key)

-- Decoding is the same as encoding
decodeB :: Bits a => [a] -> [a] -> [a]
decodeB = encodeB

-- To encode a String, we first map each character to a number,
-- then map the numbers back to characters after encoding
encode :: String -> String -> String
encode key txt = map chr $ encodeB (map ord key) (map ord txt)

-- Decoding is the same as encoding
decode :: String -> String -> String
decode = encode