Skip to content

Commit

Permalink
add set 2 challenge 12
Browse files Browse the repository at this point in the history
  • Loading branch information
ckw committed Sep 2, 2014
1 parent 494d81f commit 54dfab5
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
15 changes: 15 additions & 0 deletions cryptopals.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -181,3 +181,18 @@ executable set2ch11
, random == 1.0.1.1
hs-source-dirs: set2, src
default-language: Haskell2010

executable set2ch12
main-is: challenge12.hs
ghc-options: -Wall -O2
-- other-modules:
-- other-extensions:
build-depends: base >=4.5 && <4.6
, bytestring == 0.10.4.0
, base64-bytestring == 1.0.0.1
, containers
, cipher-aes
, dlist == 0.6.0.1
, random == 1.0.1.1
hs-source-dirs: set2, src
default-language: Haskell2010
48 changes: 48 additions & 0 deletions set2/challenge12.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
{-#LANGUAGE OverloadedStrings #-}
{-#LANGUAGE DeriveDataTypeable #-}

import Crypto.Common ( fromB64
, padBlock
, randAESKey
)
import qualified Crypto.Cipher.AES as AES
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString as BS
import Control.Applicative ((<$>))
import Data.Char (chr)
import Data.Word
import System.Random (newStdGen)

--ugh
--to run: ./dist/build/set2ch12/set2ch12

main :: IO ()
main = do key <- newStdGen >>= return . BS.pack . randAESKey
putStrLn $ (chr . fromIntegral) <$> breakECB 16 key

breakECB :: Int -> BS.ByteString -> [Word8]
breakECB blockSize key = breakECB' (blockSize - 1) [] 1
where aes = AES.initAES key
oracle ws = AES.encryptECB aes . BS.pack . padBlock 16 $ ws ++ secretText
secretText = BL.unpack . fromB64 . BL.concat $ [ "Um9sbGluJyBpbiBteSA1LjAK"
, "V2l0aCBteSByYWctdG9wIGRv"
, "d24gc28gbXkgaGFpciBjYW4g"
, "YmxvdwpUaGUgZ2lybGllcyBv"
, "biBzdGFuZGJ5IHdhdmluZyBq"
, "dXN0IHRvIHNheSBoaQpEaWQg"
, "eW91IHN0b3A/IE5vLCBJIGp1"
, "c3QgZHJvdmUgYnkK"
]
breakECB' padSz acc blk =
let pad = replicate padSz 0
pre = pad ++ acc
o = oracle pad
ebs = [ (AES.encryptECB aes . BS.pack $ pre ++ [w], w) |
w <- [0..255]
]
Just c = lookup (BS.take (blk * blockSize) o) ebs
in if blk * blockSize > length secretText
then acc
else if padSz == 0
then breakECB' (blockSize - 1) (acc ++ [c]) (blk + 1)
else breakECB' (padSz - 1) (acc ++ [c]) blk

0 comments on commit 54dfab5

Please sign in to comment.