haskell-crypto / cryptonite

lowlevel set of cryptographic primitives for haskell
Other
226 stars 139 forks source link

CBC for file #79

Open nrolland opened 8 years ago

nrolland commented 8 years ago

hi,

is there a simple example somewhere to do some file level CBC encryption ?

thank you !

vincenthz commented 8 years ago

There isn't sadly; it would be nice to start collecting some small example like this. @nrolland: care to write one maybe ? I'm happy to guide you to write the right thing.

It should roughly looks like in pseudo code:

import qualified Data.ByteString.Lazy as L
import Crypto.Error
import Crypto.Cipher

encrypt key in out = do
    let cipher = (throwCryptoError $ cipherInit key) :: AES128
    inData <- L.readFile in
    iv <- makeIV <$> getRandom 16
    let outData = loop cipher iv inData
    L.writeFile out (L.fromChunks outData)
  where loop cipher iv l =
                  let (a,b) = L.splitAt 1024 l
                   in if L.empty b
                            then cbcEncrypt cipher iv (applyPadding b)
                            else let out = cbcEncrypt cipher iv (L.toStrict a) 
                                       nextIv = makeIV $ takeLast 16 out
                                     in out : loop cipher nextIv b