Make ivAdd more constant-time

All IV bytes are processed even if accumulator is zero.
This commit is contained in:
Olivier Chéron 2017-05-31 23:31:29 +02:00
parent 07592ab237
commit edd5d94bd4

View File

@ -36,7 +36,6 @@ module Crypto.Cipher.Types.Block
--, cfb8Decrypt --, cfb8Decrypt
) where ) where
import Control.Monad (unless)
import Data.Word import Data.Word
import Data.Monoid import Data.Monoid
import Crypto.Error import Crypto.Error
@ -171,13 +170,14 @@ ivAdd (IV b) i = IV $ copy b
copy bs = B.copyAndFreeze bs $ loop i (B.length bs - 1) copy bs = B.copyAndFreeze bs $ loop i (B.length bs - 1)
loop :: Int -> Int -> Ptr Word8 -> IO () loop :: Int -> Int -> Ptr Word8 -> IO ()
loop 0 _ _ = return () loop acc ofs p
loop acc ofs p = do | ofs < 0 = return ()
v <- peek (p `plusPtr` ofs) :: IO Word8 | otherwise = do
let accv = acc + fromIntegral v v <- peek (p `plusPtr` ofs) :: IO Word8
(hi,lo) = accv `divMod` 256 let accv = acc + fromIntegral v
poke (p `plusPtr` ofs) (fromIntegral lo :: Word8) (hi,lo) = accv `divMod` 256
unless (ofs == 0) $ loop hi (ofs - 1) p poke (p `plusPtr` ofs) (fromIntegral lo :: Word8)
loop hi (ofs - 1) p
cbcEncryptGeneric :: (ByteArray ba, BlockCipher cipher) => cipher -> IV cipher -> ba -> ba cbcEncryptGeneric :: (ByteArray ba, BlockCipher cipher) => cipher -> IV cipher -> ba -> ba
cbcEncryptGeneric cipher ivini input = mconcat $ doEnc ivini $ chunk (blockSize cipher) input cbcEncryptGeneric cipher ivini input = mconcat $ doEnc ivini $ chunk (blockSize cipher) input