Skip to content

Instantly share code, notes, and snippets.

@KWMalik
Forked from supki/Main.hs
Created July 30, 2012 20:04
Show Gist options
  • Save KWMalik/3209703 to your computer and use it in GitHub Desktop.
Save KWMalik/3209703 to your computer and use it in GitHub Desktop.
Cryptography coursera class exercise #2.
{-# LANGUAGE UnicodeSyntax #-}
import Control.Applicative ((<$>))
import Control.Monad ((<=<))
import Crypto.Cipher.AES (Key, IV(..), decryptCBC, decryptCTR, initKey)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
main ∷ IO ()
main = do
mapM_ (print <=< cbc "data/key1.dat") ["data/ciphertext1.dat", "data/ciphertext2.dat"]
mapM_ (print <=< ctr "data/key2.dat") ["data/ciphertext3.dat", "data/ciphertext4.dat"]
where
cbc = decryptWith decryptCBC
ctr = decryptWith decryptCTR
decryptWith ∷ (Key → IV → ByteString → ByteString) → FilePath → FilePath → IO ByteString
decryptWith f keyfp datafp =
do key ← initKey <$> B.readFile keyfp
(iv, cipher) ← parse <$> B.readFile datafp
return $ f key iv cipher
parse ∷ ByteString → (IV, ByteString)
parse bs = (IV iv, cipher)
where
(iv, cipher) = B.splitAt 16 bs
@KWMalik
Copy link
Author

KWMalik commented Jul 30, 2012

% runhaskell Main.hs
"Basic CBC mode encryption needs padding.\b\b\b\b\b\b\b\b"
"Our implementation uses rand. IV\DLE\DLE\DLE\DLE\DLE\DLE\DLE\DLE\DLE\DLE\DLE\DLE\DLE\DLE\DLE\DLE"
"CTR mode lets you build a stream cipher from a block cipher."
"Always avoid the two time pad!"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment