praxis

Various programming exercises.
git clone git://git.jtobin.io/praxis.git
Log | Files | Refs

Cipher.hs (914B)


      1 {-# OPTIONS_GHC -Wall #-}
      2 
      3 module Cipher (encrypt, decrypt) where
      4 
      5 import Data.ByteString (ByteString)
      6 import qualified Data.ByteString as BS (pack, unpack)
      7 import Data.Bits (xor)
      8 import Data.List (unfoldr)
      9 import Data.Word (Word8)
     10 import Unsafe.Coerce (unsafeCoerce)
     11 
     12 newtype Crypted a = Crypted a
     13 
     14 instance Show a => Show (Crypted a) where
     15   show (Crypted a) = show a
     16 
     17 gen :: Integral a => a -> [Word8]
     18 gen = unsafeCoerce . map (`mod` 255) . drop 1 . unfoldr coalg where
     19   coalg j = Just (j, (1664525 * j + 1013904223) `mod` (2 ^ (32 :: Int)))
     20 
     21 toggle :: Integral a => ByteString -> a -> ByteString
     22 toggle text key = BS.pack $ zipWith xor unpacked rands where
     23   rands    = gen key
     24   unpacked = BS.unpack text
     25 
     26 encrypt :: Integral a => ByteString -> a -> Crypted ByteString
     27 encrypt text = Crypted . toggle text
     28 
     29 decrypt :: Integral a => Crypted ByteString -> a -> ByteString
     30 decrypt (Crypted text) = toggle text
     31