crypto-conduit-0.5.2.1/0000755000000000000000000000000012222545613013030 5ustar0000000000000000crypto-conduit-0.5.2.1/README0000644000000000000000000000000012222545613013676 0ustar0000000000000000crypto-conduit-0.5.2.1/crypto-conduit.cabal0000644000000000000000000000330412222545613016777 0ustar0000000000000000Cabal-version: >= 1.8 Name: crypto-conduit Version: 0.5.2.1 Synopsis: Conduit interface for cryptographic operations (from crypto-api). Homepage: https://github.com/meteficha/crypto-conduit License: BSD3 License-file: LICENSE Author: Felipe Lessa Maintainer: Felipe Lessa Category: Cryptography, Conduit Build-type: Simple Description: This package contains everything that you need to use a cryptographic package that supports the @crypto-api@ package using conduits from the @conduit@ package. Extra-source-files: README tests/runtests.hs Source-repository head Type: git Location: git://github.com/meteficha/crypto-conduit.git Flag old-crypto-api Description: Use crypto-api < 0.9. Default: False Library Hs-Source-Dirs: src Exposed-modules: Crypto.Conduit Build-depends: base >= 3 && < 5, bytestring >= 0.9, cereal >= 0.3 && < 0.5, conduit >= 1.0 && < 1.1, transformers >= 0.2 && < 0.4 if flag(old-crypto-api) Build-depends: crypto-api >= 0.8 && < 0.9 CPP-options: -DOLD_CRYPTO_API else Build-depends: crypto-api >= 0.9 && < 0.13 GHC-options: -Wall Test-suite runtests Type: exitcode-stdio-1.0 Build-depends: base, bytestring, cereal, crypto-api >= 0.12, conduit, transformers, cryptocipher >= 0.4, cryptohash-cryptoapi >= 0.1, skein >= 0.1, hspec >= 1.3, -- finally, our own package crypto-conduit GHC-options: -Wall Hs-source-dirs: tests Main-is: runtests.hs crypto-conduit-0.5.2.1/Setup.hs0000644000000000000000000000005612222545613014465 0ustar0000000000000000import Distribution.Simple main = defaultMain crypto-conduit-0.5.2.1/LICENSE0000644000000000000000000000276112222545613014043 0ustar0000000000000000Copyright (c)2012, Felipe Lessa All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Felipe Lessa nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. crypto-conduit-0.5.2.1/tests/0000755000000000000000000000000012222545613014172 5ustar0000000000000000crypto-conduit-0.5.2.1/tests/runtests.hs0000644000000000000000000001564412222545613016427 0ustar0000000000000000{-# LANGUAGE Rank2Types #-} -- from base import Control.Applicative ((<$>)) import Control.Monad.ST (runST) import Data.Word (Word8) -- from bytestring import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L -- from crypto-api import Crypto.Classes ((.::.)) import qualified Crypto.Classes as C import qualified Crypto.HMAC as C import qualified Crypto.Modes as CM --import qualified Crypto.Padding as C --import qualified Crypto.Random as C import qualified Crypto.Types as C -- from conduit import Data.Conduit import Data.Conduit.Binary (isolate) import Data.Conduit.List (sourceList, consume) -- from cryptohash-cryptoapi import Crypto.Hash.CryptoAPI ( MD2, MD4, MD5, RIPEMD160, SHA1, SHA224 , SHA256, SHA384, SHA512, Tiger ) -- from skein import qualified Crypto.Skein as Skein -- from hspec import Test.Hspec import Test.Hspec.QuickCheck -- from this package import Crypto.Conduit main :: IO () main = hspec $ do describe "cryptohash's MD2" $ testHash (undefined :: MD2) describe "cryptohash's MD4" $ testHash (undefined :: MD4) describe "cryptohash's MD5" $ testHash (undefined :: MD5) describe "cryptohash's RIPEMD160" $ testHash (undefined :: RIPEMD160) describe "cryptohash's SHA1" $ testHash (undefined :: SHA1) describe "cryptohash's SHA224" $ testHash (undefined :: SHA224) describe "cryptohash's SHA256" $ testHash (undefined :: SHA256) describe "cryptohash's SHA384" $ testHash (undefined :: SHA384) describe "cryptohash's SHA512" $ testHash (undefined :: SHA512) describe "cryptohash's Tiger" $ testHash (undefined :: Tiger) describe "skein's Skein_512_512" $ testHash (undefined :: Skein.Skein_512_512) describe "skein's Skein_1024_1024" $ testHash (undefined :: Skein.Skein_1024_1024) describe "skein's Skein_256_256" $ testHash (undefined :: Skein.Skein_256_256) describe "skein's Skein_256_128" $ testHash (undefined :: Skein.Skein_256_128) describe "skein's Skein_256_160" $ testHash (undefined :: Skein.Skein_256_160) describe "skein's Skein_256_224" $ testHash (undefined :: Skein.Skein_256_224) describe "skein's Skein_512_128" $ testHash (undefined :: Skein.Skein_512_128) describe "skein's Skein_512_160" $ testHash (undefined :: Skein.Skein_512_160) describe "skein's Skein_512_224" $ testHash (undefined :: Skein.Skein_512_224) describe "skein's Skein_512_256" $ testHash (undefined :: Skein.Skein_512_256) describe "skein's Skein_512_384" $ testHash (undefined :: Skein.Skein_512_384) describe "skein's Skein_1024_384" $ testHash (undefined :: Skein.Skein_1024_384) describe "skein's Skein_1024_512" $ testHash (undefined :: Skein.Skein_1024_512) ---------------------------------------------------------------------- testHash :: C.Hash ctx d => d -> Spec testHash d = do prop "works with sinkHash" $ \str -> prop_sinkHash d (L.pack str) prop "works with sinkHmac" $ \key str -> prop_sinkHmac d (C.MacKey $ B.pack key) (L.pack str) prop_sinkHash :: C.Hash ctx d => d -> L.ByteString -> Bool prop_sinkHash d input = let d1 = runPureResource $ sourceList (L.toChunks input) $$ sinkHash d2 = C.hashFunc d input in d1 == d2 prop_sinkHmac :: C.Hash ctx d => d -> C.MacKey ctx d -> L.ByteString -> Bool prop_sinkHmac d mackey input = let d1 = runPureResource $ sourceList (L.toChunks input) $$ sinkHmac mackey d2 = C.hmac mackey input `asTypeOf` d in d1 == d2 ---------------------------------------------------------------------- testBlockCipher :: C.BlockCipher k => k -> Spec testBlockCipher undefinedKey = do let Just k = let len = (C.keyLength .::. k) `div` 8 in C.buildKey (B.replicate len 0xFF) `asTypeOf` Just undefinedKey blockSize = (C.blockSize .::. k) `div` 8 prop "works with conduitEncryptEcb" $ testBlockCipherConduit (Just blockSize) (conduitEncryptEcb k) (CM.ecb k) prop "works with conduitDecryptEcb" $ testBlockCipherConduit (Just blockSize) (conduitDecryptEcb k) (CM.unEcb k) prop "works with conduitEncryptCbc" $ testBlockCipherConduit (Just blockSize) (conduitEncryptCbc k CM.zeroIV) (fst . CM.cbc k CM.zeroIV) prop "works with conduitDecryptCbc" $ testBlockCipherConduit (Just blockSize) (conduitDecryptCbc k CM.zeroIV) (fst . CM.unCbc k CM.zeroIV) prop "works with conduitEncryptCfb" $ testBlockCipherConduit (Just blockSize) (conduitEncryptCfb k CM.zeroIV) (fst . CM.cfb k CM.zeroIV) prop "works with conduitDecryptCfb" $ testBlockCipherConduit (Just blockSize) (conduitDecryptCfb k CM.zeroIV) (fst . CM.unCfb k CM.zeroIV) prop "works with conduitEncryptOfb" $ testBlockCipherConduit (Just blockSize) (conduitEncryptOfb k CM.zeroIV) (fst . CM.ofb k CM.zeroIV) prop "works with conduitDecryptOfb" $ testBlockCipherConduit (Just blockSize) (conduitDecryptOfb k CM.zeroIV) (fst . CM.unOfb k CM.zeroIV) prop "works with conduitEncryptCtr" $ testBlockCipherConduit Nothing (conduitEncryptCtr k CM.zeroIV C.incIV) (fst . CM.ctr C.incIV k CM.zeroIV) prop "works with conduitDecryptCtr" $ testBlockCipherConduit Nothing (conduitDecryptCtr k CM.zeroIV C.incIV) (fst . CM.unCtr C.incIV k CM.zeroIV) it "works with sourceCtr" $ let len :: Num a => a len = 1024 * 1024 -- 1 MiB r1 = runPureResource $ sourceCtr k CM.zeroIV $$ isolate len =$ consumeAsLazy r2 = fst $ CM.ctr C.incIV k CM.zeroIV (L.replicate len 0) in r1 == r2 prop "works with sinkCbcMac" $ \input -> let inputL = fixBlockedSize blockSize (L.pack input) r1 = runPureResource $ sourceList (L.toChunks inputL) $$ sinkCbcMac k r2 = C.encode $ snd $ CM.cbc k CM.zeroIV inputL in r1 == r2 testBlockCipherConduit :: Maybe C.ByteLength -- ^ Fix input length to be a multiple of the block size? -> (forall m. Monad m => Conduit B.ByteString m B.ByteString) -> (L.ByteString -> L.ByteString) -> [Word8] -> Bool testBlockCipherConduit mblockSize conduit lazyfun input = let inputL = maybe id fixBlockedSize mblockSize (L.pack input) r1 = runPureResource $ sourceList (L.toChunks inputL) $$ conduit =$ consumeAsLazy r2 = lazyfun inputL in r1 == r2 ---------------------------------------------------------------------- runPureResource :: (forall m. Monad m => m a) -> a runPureResource r = runST r consumeAsLazy :: Monad m => Sink B.ByteString m L.ByteString consumeAsLazy = L.fromChunks <$> consume fixBlockedSize :: C.ByteLength -> L.ByteString -> L.ByteString fixBlockedSize blockSize lbs = let blockSize' = fromIntegral blockSize toFill = let leftovers = L.length lbs `mod` blockSize' in if leftovers == 0 then 0 else blockSize' - leftovers in L.append lbs $ L.replicate toFill 0xFF crypto-conduit-0.5.2.1/src/0000755000000000000000000000000012222545613013617 5ustar0000000000000000crypto-conduit-0.5.2.1/src/Crypto/0000755000000000000000000000000012222545613015077 5ustar0000000000000000crypto-conduit-0.5.2.1/src/Crypto/Conduit.hs0000644000000000000000000003744612222545613017056 0ustar0000000000000000{-# LANGUAGE BangPatterns, CPP, RankNTypes #-} -- | This module contains wrappers for cryptographic functions -- using the @conduit@ package. Currently there is support for -- hashes, HMACs and many modes of block ciphers (but not -- everything @crypto-api@ supports has a counterpart here). -- All functions on this package work in constant memory. module Crypto.Conduit ( -- * Cryptographic hash functions sinkHash , hashFile -- * Hash-based message authentication code (HMAC) , sinkHmac -- * Block ciphers -- ** Electronic codebook mode (ECB) , conduitEncryptEcb , conduitDecryptEcb -- ** Cipher-block chaining mode (CBC) , conduitEncryptCbc , conduitDecryptCbc -- ** Cipher feedback mode (CFB) , conduitEncryptCfb , conduitDecryptCfb -- ** Output feedback mode (OFB) , conduitEncryptOfb , conduitDecryptOfb -- ** Counter mode (CTR) , conduitEncryptCtr , conduitDecryptCtr , sourceCtr -- ** Cipher-block chaining message authentication code (CBC-MAC) , sinkCbcMac -- * Internal helpers , blocked , BlockMode(..) , Block(..) ) where -- from base import Control.Arrow (first) import Data.Bits (xor) -- from bytestring import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L -- from cereal import qualified Data.Serialize as S -- from crypto-api import Crypto.Classes ((.::.)) import qualified Crypto.Classes as C import qualified Crypto.HMAC as C import qualified Crypto.Modes as C --import qualified Crypto.Padding as C --import qualified Crypto.Random as C import qualified Crypto.Types as C -- from conduit import Data.Conduit import Data.Conduit.Binary (sourceFile) -- from transformers import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Trans.Class (lift) -- | Helper to get our return type. getType :: Monad m => sink input m output -> output getType = undefined ---------------------------------------------------------------------- -- | A 'Sink' that hashes a stream of 'B.ByteString'@s@ and -- creates a digest @d@. sinkHash :: (Monad m, C.Hash ctx d) => Consumer B.ByteString m d sinkHash = self where self = sink C.initialCtx sink ctx = do x <- getBlock AnyMultiple blockSize case x of Full bs -> let !ctx' = C.updateCtx ctx bs in sink ctx' LastOne bs -> return $! C.finalize ctx bs blockSize = (C.blockLength .::. getType self) `div` 8 getBlock :: Monad m => BlockMode -> C.ByteLength -> Consumer B.ByteString m Block getBlock blockMode blockSize = go id where go front = await >>= maybe (close front) (push front) push front bs' = case compare (B.length bs) blockSize of LT -> go $ B.append bs EQ -> return $ Full bs GT -> leftover y >> return (Full x) where bs = front bs' (x, y) = B.splitAt splitter bs splitter = case blockMode of StrictBlockSize -> blockSize AnyMultiple -> B.length bs - (B.length bs `mod` blockSize) close front = return $ LastOne $ front B.empty -- | Hashes the whole contents of the given file in constant -- memory. This function is just a convenient wrapper around -- 'sinkHash' defined as: -- -- @ -- hashFile fp = 'liftIO' $ 'runResourceT' ('sourceFile' fp '$$' 'sinkHash') -- @ hashFile :: (MonadIO m, C.Hash ctx d) => FilePath -> m d hashFile fp = liftIO $ runResourceT (sourceFile fp $$ sinkHash) ---------------------------------------------------------------------- -- | A 'Sink' that computes the HMAC of a stream of -- 'B.ByteString'@s@ and creates a digest @d@. sinkHmac :: (Monad m, C.Hash ctx d) => #if OLD_CRYPTO_API C.MacKey #else C.MacKey ctx d #endif -> Consumer B.ByteString m d sinkHmac (C.MacKey key) = sink where --------- Taken and modified from Crypto.HMAC: key' = case B.length key `compare` blockSize of GT -> B.append (S.encode $ C.hashFunc' d key) (B.replicate (blockSize - outputSize) 0x00) EQ -> key LT -> B.append key (B.replicate (blockSize - B.length key) 0x00) ko = B.map (`xor` 0x5c) key' ki = B.map (`xor` 0x36) key' --------- sink = go $ C.updateCtx C.initialCtx ki go ctx = do x <- getBlock AnyMultiple blockSize case x of Full bs -> let !ctx' = C.updateCtx ctx bs in go ctx' LastOne bs -> let !inner = C.finalize ctx bs `asTypeOf` d !outer = C.hash $ L.fromChunks [ko, S.encode inner] in return outer d = getType sink blockSize = (C.blockLength .::. d) `div` 8 outputSize = (C.outputLength .::. d) `div` 8 ---------------------------------------------------------------------- -- | A 'Conduit' that encrypts a stream of 'B.ByteString'@s@ -- using ECB mode. Expects the input length to be a multiple of -- the block size of the cipher and fails otherwise. (Note that -- ECB has many undesirable cryptographic properties, please -- avoid it if you don't know what you're doing.) conduitEncryptEcb :: (Monad m, C.BlockCipher k) => k -- ^ Cipher key. -> Conduit B.ByteString m B.ByteString conduitEncryptEcb k = blockCipherConduit k AnyMultiple () (\_ input -> ((), C.encryptBlock k input)) (\_ _ -> fail "conduitEncryptEcb: input has an incomplete final block.") -- | A 'Conduit' that decrypts a stream of 'B.ByteString'@s@ -- using ECB mode. Expects the input length to be a multiple of -- the block size of the cipher and fails otherwise. conduitDecryptEcb :: (Monad m, C.BlockCipher k) => k -- ^ Cipher key. -> Conduit B.ByteString m B.ByteString conduitDecryptEcb k = blockCipherConduit k AnyMultiple () (\_ input -> ((), C.decryptBlock k input)) (\_ _ -> fail "conduitDecryptEcb: input has an incomplete final block.") ---------------------------------------------------------------------- -- | A 'Conduit' that encrypts a stream of 'B.ByteString'@s@ -- using CBC mode. Expects the input length to be a multiple of -- the block size of the cipher and fails otherwise. conduitEncryptCbc :: (Monad m, C.BlockCipher k) => k -- ^ Cipher key. -> C.IV k -- ^ Initialization vector. -> Conduit B.ByteString m B.ByteString conduitEncryptCbc k iv = blockCipherConduit k StrictBlockSize (S.encode iv) (\iv' input -> let output = C.encryptBlock k (iv' `zwp` input) in (output, output)) (\_ _ -> fail "conduitEncryptCbc: input has an incomplete final block.") -- | A 'Conduit' that decrypts a stream of 'B.ByteString'@s@ -- using CBC mode. Expects the input length to be a multiple of -- the block size of the cipher and fails otherwise. conduitDecryptCbc :: (Monad m, C.BlockCipher k) => k -- ^ Cipher key. -> C.IV k -- ^ Initialization vector. -> Conduit B.ByteString m B.ByteString conduitDecryptCbc k iv = blockCipherConduit k StrictBlockSize (S.encode iv) (\iv' input -> let output = C.decryptBlock k input `zwp` iv' in (input, output)) (\_ _ -> fail "conduitDecryptCbc: input has an incomplete final block.") ---------------------------------------------------------------------- -- | A 'Conduit' that encrypts a stream of 'B.ByteString'@s@ -- using CFB mode. Expects the input length to be a multiple of -- the block size of the cipher and fails otherwise. conduitEncryptCfb :: (Monad m, C.BlockCipher k) => k -- ^ Cipher key. -> C.IV k -- ^ Initialization vector. -> Conduit B.ByteString m B.ByteString conduitEncryptCfb k iv = blockCipherConduit k StrictBlockSize (S.encode iv) (\iv' input -> let output = C.encryptBlock k iv' `zwp` input in (output, output)) (\_ _ -> fail "conduitEncryptCfb: input has an incomplete final block.") -- | A 'Conduit' that decrypts a stream of 'B.ByteString'@s@ -- using CFB mode. Expects the input length to be a multiple of -- the block size of the cipher and fails otherwise. conduitDecryptCfb :: (Monad m, C.BlockCipher k) => k -- ^ Cipher key. -> C.IV k -- ^ Initialization vector. -> Conduit B.ByteString m B.ByteString conduitDecryptCfb k iv = blockCipherConduit k StrictBlockSize (S.encode iv) (\iv' input -> let output = C.encryptBlock k iv' `zwp` input in (input, output)) (\_ _ -> fail "conduitDecryptCfb: input has an incomplete final block.") ---------------------------------------------------------------------- -- | A 'Conduit' that encrypts a stream of 'B.ByteString'@s@ -- using OFB mode. Expects the input length to be a multiple of -- the block size of the cipher and fails otherwise. conduitEncryptOfb :: (Monad m, C.BlockCipher k) => k -- ^ Cipher key. -> C.IV k -- ^ Initialization vector. -> Conduit B.ByteString m B.ByteString conduitEncryptOfb k iv = blockCipherConduit k StrictBlockSize (S.encode iv) (\iv' input -> let inter = C.encryptBlock k iv' in (inter, inter `zwp` input)) (\_ _ -> fail "conduitEncryptOfb: input has an incomplete final block.") -- | Synonym for 'conduitEncryptOfb', since for OFB mode both -- encryption and decryption are the same. conduitDecryptOfb :: (Monad m, C.BlockCipher k) => k -- ^ Cipher key. -> C.IV k -- ^ Initialization vector. -> Conduit B.ByteString m B.ByteString conduitDecryptOfb = conduitEncryptOfb ---------------------------------------------------------------------- -- | A 'Conduit' that encrypts a stream of 'B.ByteString'@s@ -- using CTR mode. The input may have any length, even -- non-multiples of the block size. conduitEncryptCtr :: (Monad m, C.BlockCipher k) => k -- ^ Cipher key. -> C.IV k -- ^ Initialization vector. -> (C.IV k -> C.IV k) -- ^ Increment counter ('C.incIV' is recommended) -> Conduit B.ByteString m B.ByteString conduitEncryptCtr k iv incIV = blockCipherConduit k StrictBlockSize iv (\iv' input -> let !iv'' = incIV iv' output = C.encryptBlock k (S.encode iv') `zwp` input in (iv'', output)) (\iv' input -> let output = C.encryptBlock k (S.encode iv') `zwp` input in return output) -- | Synonym for 'conduitEncryptCtr', since for CTR mode both -- encryption and decryption are the same. conduitDecryptCtr :: (Monad m, C.BlockCipher k) => k -- ^ Cipher key. -> C.IV k -- ^ Initialization vector. -> (C.IV k -> C.IV k) -- ^ Increment counter ('C.incIV' is recommended) -> Conduit B.ByteString m B.ByteString conduitDecryptCtr = conduitEncryptCtr -- | An infinite stream of bytes generated by a block cipher on -- CTR mode. sourceCtr :: (Monad m, C.BlockCipher k) => k -- ^ Cipher key. -> C.IV k -- ^ Initialization vector. -> Producer m B.ByteString sourceCtr k = loop where loop iv = yield block >> loop iv' where !iv' = C.incIV iv block = C.encryptBlock k $ S.encode iv ---------------------------------------------------------------------- -- | A 'Sink' that computes the CBC-MAC of a stream of -- 'B.ByteString'@s@ and creates a digest (already encoded in a -- 'B.ByteString', since we're using a block cipher). Expects -- the input length to be a multiple of the block size of the -- cipher and fails otherwise. (Note that CBC-MAC is not secure -- for variable-length messages.) sinkCbcMac :: (Monad m, C.BlockCipher k) => k -- ^ Cipher key. -> Consumer B.ByteString m B.ByteString sinkCbcMac k = go $ B.replicate blockSize 0 where go iv = do x <- getBlock StrictBlockSize blockSize case x of Full input -> let !iv' = C.encryptBlock k (iv `zwp` input) in go iv' LastOne input | B.null input -> return iv | otherwise -> lift $ fail "sinkCbcMac: input has an incomplete final block." blockSize = (C.blockSize .::. k) `div` 8 ---------------------------------------------------------------------- -- | A 'Conduit' that takes arbitrary 'B.ByteString'@s@ and -- outputs 'Block'@s@. Each 'Full' block will have a length that -- is multiple of the given block size (either exactly the block -- size or a multiple of at least 1x the block size, depending on -- the 'BlockMode'). All 'Block'@s@ beside the last one will be -- 'Full'. The last block will always be 'LastOne' with less -- bytes than the block size, possibly zero. blocked :: Monad m => BlockMode -> C.ByteLength -- ^ Block size -> Conduit B.ByteString m Block blocked mode blockSize = go B.empty where go x = await >>= maybe (close x) (push x) block = case mode of StrictBlockSize -> blockStrict id AnyMultiple -> blockAny where blockStrict front bs | B.length bs < blockSize = (front [], bs) | otherwise = blockStrict (front . (Full this :)) rest where (this, rest) = B.splitAt blockSize bs blockAny bs | n >= 1 = first ((:[]) . Full) $ B.splitAt (n * blockSize) bs | otherwise = ([], bs) where n = B.length bs `div` blockSize append bs1 bs2 | B.null bs1 = bs2 | otherwise = B.append bs1 bs2 push acc x = mapM_ yield blks >> go rest where (blks, rest) = block bs bs = append acc x close acc = yield (LastOne acc) -- | How 'Block's should be returned, either with strictly the -- block size or with a multiple of at least 1x the block size. data BlockMode = StrictBlockSize | AnyMultiple deriving (Eq, Ord, Show, Enum) -- | A block returned by 'blocked'. data Block = Full B.ByteString | LastOne B.ByteString deriving (Eq, Ord, Show) -- | Constructs a 'Conduit' for a 'BlockCipher'. blockCipherConduit :: (Monad m, C.BlockCipher k) => k -- ^ Cipher key (not used, just for getting block size). -> BlockMode -> s -- ^ Initial state. -> (s -> B.ByteString -> (s, B.ByteString)) -- ^ Encrypt block. -> (s -> B.ByteString -> m B.ByteString) -- ^ Final encryption. -> Conduit B.ByteString m B.ByteString blockCipherConduit key mode initialState apply final = go initialState where blockSize = (C.blockSize .::. key) `div` 8 go state = do x <- getBlock mode blockSize case x of Full input -> do let (!state', !output) = apply state input yield output go state' LastOne input | B.null input -> return () >> finish | otherwise -> lift (final state input) >>= yield >> finish finish = await >>= maybe (return ()) (const finish) -- | zipWith xor + pack -- -- As a result of rewrite rules, this should automatically be -- optimized (at compile time) to use the bytestring libraries -- 'zipWith'' function. -- -- Taken from crypto-api. zwp :: B.ByteString -> B.ByteString -> B.ByteString zwp a = B.pack . B.zipWith xor a {-# INLINEABLE zwp #-}