packages feed

crypton 2.2.6 → 2.2.7

raw patch · 72 files changed

+793/−213 lines, 72 filesdep ~base16PVP ok

version bump matches the API change (PVP)

Dependency ranges changed: base16

API changes (from Hackage documentation)

+ Crypto.PubKey.RSA.Types: instance Crypto.Debug.DebugShow Crypto.PubKey.RSA.Types.Blinder

Files

CHANGELOG.md view
@@ -1,5 +1,45 @@ # CHANGELOG for crypton +## 2.2.7++Fixes from the 2026-11 review, backported from the 2.3 series.  Salsa now+refuses a 96-bit nonce (#379), and KeyedBlake2 uses a key longer than the+digest whole instead of truncating it, refusing one past the BLAKE2 maximum+(#382).++* fix(blake2): treat an empty MAC key as the unkeyed hash+  [#371](https://github.com/kazu-yamamoto/crypton/pull/371)+* fix(whirlpool): count bits in 64 bits so 256 MiB updates are hashed+  [#372](https://github.com/kazu-yamamoto/crypton/pull/372)+* fix(ocb): carry the block index across incremental calls+  [#373](https://github.com/kazu-yamamoto/crypton/pull/373)+* fix: low-severity issues from the 2026-11 audit+  [#374](https://github.com/kazu-yamamoto/crypton/pull/374)+* fix: check the IV length in AES CBC/XTS+  [#375](https://github.com/kazu-yamamoto/crypton/pull/375)+* fix(entropy): refuse a negative length instead of writing past an empty buffer+  [#376](https://github.com/kazu-yamamoto/crypton/pull/376)+* fix(chachapoly1305): stop incrementNonce's carry at the end of the nonce+  [#377](https://github.com/kazu-yamamoto/crypton/pull/377)+* fix(cast5): refuse ECB input that is not whole blocks+  [#378](https://github.com/kazu-yamamoto/crypton/pull/378)+* fix(salsa): refuse a 96-bit nonce+  [#379](https://github.com/kazu-yamamoto/crypton/pull/379)+* fix(hash): keep hashFinalizePrefix's lengths inside 32 bits+  [#380](https://github.com/kazu-yamamoto/crypton/pull/380)+* fix(ecc): hide the P-384/P-521 scalar in Show+  [#381](https://github.com/kazu-yamamoto/crypton/pull/381)+* fix(keyed-blake2): take keys up to the BLAKE2 maximum, not the digest size+  [#382](https://github.com/kazu-yamamoto/crypton/pull/382)+* fix(elgamal): refuse c1 of 1 or p-1 in decrypt+  [#383](https://github.com/kazu-yamamoto/crypton/pull/383)+* fix(chachapoly1305): pad the AEAD header once, not after each piece+  [#384](https://github.com/kazu-yamamoto/crypton/pull/384)+* fix(cabal): leave the extension paths out without use_target_attributes+  [#385](https://github.com/kazu-yamamoto/crypton/pull/385)+* Require the bcrypt cost to be two digits+  [#388](https://github.com/kazu-yamamoto/crypton/pull/388)+ ## 2.2.6  **Fixes from a security review.**  Inputs that are invalid by the
Crypto/Cipher/AES/GCM.hs view
@@ -211,7 +211,8 @@ encryptWithMask (Context aes gk) (HeaderKey hp) nonce aad input taglen off outp maskp     | tooLongForC aad input = return False     | badNonce nonce = return False-    | off < 0 || badTagLength taglen || off + 16 > B.length input + taglen =+    -- subtract rather than add, so that an offset near maxBound cannot wrap+    | off < 0 || badTagLength taglen || off > B.length input + taglen - 16 =         return False     | otherwise = do         gcmFullEncryptMask aes gk hp nonce aad input taglen off outp maskp
Crypto/Cipher/AES/Primitive.hs view
@@ -174,7 +174,7 @@ sizeGCMKey = 832  sizeOCB :: Int-sizeOCB = 160+sizeOCB = 176  sizeCCM :: Int sizeCCM = 84@@ -404,6 +404,10 @@     (nbBlocks, r) = len `quotRem` 16     len = B.length input +-- The C reads a whole block of IV, whatever length it was given.+ivLengthMessage :: Int -> String+ivLengthMessage n = "AES error: IV length must be block size (16). Its length is: " ++ show n+ {-# INLINE doCBC #-} doCBC     :: ByteArray ba@@ -414,6 +418,7 @@     -> ba doCBC f ctx (IV iv) input     | B.overCLength nbBlocks = error tooLongMessage+    | B.length iv /= 16 = error (ivLengthMessage (B.length iv))     | len == 0 = B.empty     | r /= 0 =         error $@@ -438,6 +443,7 @@     -> ba doXTS f (key1, key2) iv spoint input     | B.overCLength nbBlocks = error tooLongMessage+    | B.length iv /= 16 = error (ivLengthMessage (B.length iv))     | len == 0 = B.empty     | r /= 0 =         error $
Crypto/Cipher/Blowfish/Primitive.hs view
@@ -31,7 +31,7 @@ import Crypto.Internal.Compat import Crypto.Internal.Imports import Foreign.C.Types (CInt (..))-import Foreign.Ptr (Ptr)+import Foreign.Ptr (Ptr, plusPtr)  -- | The key schedule: the P array and the four S boxes, as the C keeps them. newtype Context = Context ScrubbedBytes@@ -81,7 +81,10 @@     | otherwise = unsafeDoIO $         B.alloc len $ \out ->             B.withByteArray ctx $ \c ->-                B.withByteArray input $ \i -> f c out i (fromIntegral len)+                B.withByteArray input $ \i ->+                    -- the C takes a uint32_t length, so go in pieces+                    B.inCLengths len $ \off n ->+                        f c (out `plusPtr` off) (i `plusPtr` off) (fromIntegral n)   where     len = B.length input 
Crypto/Cipher/CAST5.hs view
@@ -11,8 +11,9 @@ import Crypto.Cipher.CAST5.Primitive import Crypto.Cipher.Types import Crypto.Error-import Crypto.Internal.ByteArray (ByteArrayAccess)+import Crypto.Internal.ByteArray (ByteArray, ByteArrayAccess) import qualified Crypto.Internal.ByteArray as B+import Data.Word (Word64)  -- | CAST5 block cipher (also known as CAST-128).  Key is between -- 40 and 128 bits.@@ -25,8 +26,17 @@  instance BlockCipher CAST5 where     blockSize _ = 8-    ecbEncrypt (CAST5 k) = B.mapAsWord64 (encrypt k)-    ecbDecrypt (CAST5 k) = B.mapAsWord64 (decrypt k)+    ecbEncrypt (CAST5 k) = mapBlocks (encrypt k)+    ecbDecrypt (CAST5 k) = mapBlocks (decrypt k)++-- | 'B.mapAsWord64' leaves a partial last block of the output unwritten.+mapBlocks :: ByteArray ba => (Word64 -> Word64) -> ba -> ba+mapBlocks operation input+    | B.length input `mod` 8 /= 0 =+        error $+            "Crypto.Cipher.CAST5: input length must be a multiple of block size (8). Its length is: "+                ++ show (B.length input)+    | otherwise = B.mapAsWord64 operation input  initCAST5 :: ByteArrayAccess key => key -> CryptoFailable CAST5 initCAST5 bs
Crypto/Cipher/Camellia/Primitive.hs view
@@ -23,7 +23,7 @@ import qualified Crypto.Internal.ByteArray as B import Crypto.Internal.Compat (unsafeDoIO) import Data.Word-import Foreign.Ptr (Ptr)+import Foreign.Ptr (Ptr, plusPtr)  -- | The subkeys of RFC 3713 section 2.2: kw, k and ke, as 26 64-bit words. newtype Camellia = Camellia Bytes@@ -68,7 +68,9 @@         B.alloc len $ \out ->             B.withByteArray sched $ \ks ->                 B.withByteArray input $ \inp ->-                    f out ks inp (fromIntegral (len `div` blockBytes))+                    -- the C takes a uint32_t block count, so go in pieces+                    B.inCLengths len $ \off n ->+                        f (out `plusPtr` off) ks (inp `plusPtr` off) (fromIntegral (n `div` blockBytes))   where     len = B.length input 
Crypto/Cipher/ChaChaPoly1305.hs view
@@ -88,6 +88,7 @@         !Poly1305.State         !Word64 -- AAD length         !Word64 -- ciphertext length+        !Word64 -- most ciphertext the block counter allows  -- | A ChaChaPoly1305 State. type ChaCha20Poly1305 = State@@ -165,15 +166,15 @@  incrementNonce' :: Bytes -> Int -> Bytes incrementNonce' b offset = B.copyAndFreeze b $ \s ->-    loop s (s `plusPtr` offset)+    loop (s `plusPtr` offset) (B.length b - offset)   where-    loop :: Ptr Word8 -> Ptr Word8 -> IO ()-    loop s p-        | s == (p `plusPtr` (B.length b - offset - 1)) = peek s >>= poke s . (+) 1-        | otherwise = do-            r <- (+) 1 <$> peek p-            poke p r-            when (r == 0) $ loop s (p `plusPtr` 1)+    -- the carry stops at the last byte; all 0xff wraps to all zero+    loop :: Ptr Word8 -> Int -> IO ()+    loop _ 0 = return ()+    loop p n = do+        r <- (+) 1 <$> peek p+        poke p r+        when (r == 0) $ loop (p `plusPtr` 1) (n - 1)  -- | Initialize a new ChaChaPoly1305 State --@@ -192,14 +193,16 @@     | otherwise = CryptoPassed $ Key $ B.convert k  initialize :: Key -> Nonce -> State-initialize k (Nonce8 nonce) = initialize' k nonce-initialize k (Nonce12 nonce) = initialize' k nonce+initialize k (Nonce8 nonce) = initialize' maxBound k nonce+-- RFC 8439: with a 96-bit nonce the counter is 32 bits and block 0 is the+-- Poly1305 key, so a message is at most 2^38 - 64 bytes+initialize k (Nonce12 nonce) = initialize' (2 ^ (38 :: Int) - 64) k nonce -initialize' :: Key -> Bytes -> State-initialize' k nonce = initFromRootState (ChaCha.initialize 20 k nonce)+initialize' :: Word64 -> Key -> Bytes -> State+initialize' limit k nonce = initFromRootState limit (ChaCha.initialize 20 k nonce) -initFromRootState :: ChaCha.State -> State-initFromRootState rootState = State encState polyState 0 0+initFromRootState :: Word64 -> ChaCha.State -> State+initFromRootState limit rootState = State encState polyState 0 0 limit   where     (polyKey, encState) = ChaCha.generate rootState 64     -- 64 bytes are generated so the ChaCha state advances a whole block, and@@ -211,7 +214,7 @@ -- The key length needs to be 256 bits, and the nonce -- procured using `nonce24`. initializeX :: Key -> XNonce -> State-initializeX k (Nonce24 nonce) = initFromRootState (ChaCha.initializeX 20 k nonce)+initializeX k (Nonce24 nonce) = initFromRootState maxBound (ChaCha.initializeX 20 k nonce)  -- | Append Authenticated Data to the State and return -- the new modified State.@@ -219,24 +222,26 @@ -- Once no further call to this function need to be make, -- the user should call 'finalizeAAD' appendAAD :: ByteArrayAccess ba => ba -> State -> State-appendAAD ba (State encState macState aadLength plainLength) =-    State encState newMacState newLength plainLength+appendAAD ba (State encState macState aadLength plainLength limit) =+    State encState newMacState newLength plainLength limit   where     newMacState = Poly1305.update macState ba     newLength = aadLength + fromIntegral (B.length ba)  -- | Finalize the Authenticated Data and return the finalized State finalizeAAD :: State -> State-finalizeAAD (State encState macState aadLength plainLength) =-    State encState newMacState aadLength plainLength+finalizeAAD (State encState macState aadLength plainLength limit) =+    State encState newMacState aadLength plainLength limit   where     newMacState = Poly1305.update macState $ pad16 aadLength  -- | Encrypt a piece of data and returns the encrypted Data and the -- updated State. encrypt :: ByteArray ba => ba -> State -> (ba, State)-encrypt input (State encState macState aadLength plainLength) =-    (output, State newEncState newMacState aadLength newPlainLength)+encrypt input (State encState macState aadLength plainLength limit)+    | tooLong plainLength limit input = error tooLongMessage+    | otherwise =+        (output, State newEncState newMacState aadLength newPlainLength limit)   where     (output, newEncState) = ChaCha.combine encState input     newMacState = Poly1305.update macState output@@ -245,16 +250,26 @@ -- | Decrypt a piece of data and returns the decrypted Data and the -- updated State. decrypt :: ByteArray ba => ba -> State -> (ba, State)-decrypt input (State encState macState aadLength plainLength) =-    (output, State newEncState newMacState aadLength newPlainLength)+decrypt input (State encState macState aadLength plainLength limit)+    | tooLong plainLength limit input = error tooLongMessage+    | otherwise =+        (output, State newEncState newMacState aadLength newPlainLength limit)   where     (output, newEncState) = ChaCha.combine encState input     newMacState = Poly1305.update macState input     newPlainLength = plainLength + fromIntegral (B.length input) +-- Past the limit the 32-bit counter would carry into the nonce, and the+-- keystream would be that of the next nonce.+tooLong :: ByteArrayAccess ba => Word64 -> Word64 -> ba -> Bool+tooLong used limit input = fromIntegral (B.length input) > limit - used++tooLongMessage :: String+tooLongMessage = "ChaChaPoly1305: message longer than the nonce's counter allows"+ -- | Generate an authentication tag from the State. finalize :: State -> Poly1305.Auth-finalize (State _ macState aadLength plainLength) =+finalize (State _ macState aadLength plainLength _) =     Poly1305.finalize $         Poly1305.updates             macState@@ -269,12 +284,28 @@     => k -> n -> CryptoFailable (AEAD ChaCha20Poly1305) aeadChacha20poly1305Init k nonce = do     st0 <- initialize <$> key k <*> nonce12 nonce-    return $ AEAD model st0+    return $ AEAD model (AEADState False st0)   where     model =         AEADModeImpl-            { aeadImplAppendHeader = \st aad -> finalizeAAD $ appendAAD aad st-            , aeadImplEncrypt = \st plain -> encrypt plain st-            , aeadImplDecrypt = \st cipher -> decrypt cipher st-            , aeadImplFinalize = \st _ -> let Poly1305.Auth tag = finalize st in AuthTag tag+            { aeadImplAppendHeader = \(AEADState done st) aad ->+                -- after the message, as before: the header is padded at once+                if done+                    then AEADState True (finalizeAAD $ appendAAD aad st)+                    else AEADState False (appendAAD aad st)+            , aeadImplEncrypt = \st plain ->+                AEADState True <$> encrypt plain (headerDone st)+            , aeadImplDecrypt = \st cipher ->+                AEADState True <$> decrypt cipher (headerDone st)+            , aeadImplFinalize = \st _ ->+                let Poly1305.Auth tag = finalize (headerDone st) in AuthTag tag             }++-- | The state behind the 'AEAD' interface, which may append the header in+-- several pieces: RFC 8439 pads the header as a whole, so the padding waits+-- for the message or the tag.  'True' once it has been added.+data AEADState = AEADState !Bool !State++headerDone :: AEADState -> State+headerDone (AEADState True st) = st+headerDone (AEADState False st) = finalizeAAD st
Crypto/Cipher/DES/Primitive.hs view
@@ -67,12 +67,14 @@         B.alloc len $ \out ->             B.withByteArray sched $ \ks ->                 B.withByteArray input $ \inp ->-                    c_des_ecb-                        out-                        ks-                        (fromIntegral (B.length sched `div` stageSize))-                        inp-                        (fromIntegral (len `div` blockBytes))+                    -- the C takes a uint32_t block count, so go in pieces+                    B.inCLengths len $ \off n ->+                        c_des_ecb+                            (out `plusPtr` off)+                            ks+                            (fromIntegral (B.length sched `div` stageSize))+                            (inp `plusPtr` off)+                            (fromIntegral (n `div` blockBytes))   where     len = B.length input 
Crypto/Cipher/RC4.hs view
@@ -75,10 +75,14 @@     -- ^ The key     -> State     -- ^ The RC4 context with the key mixed in-initialize key = unsafeDoIO $ do-    st <- B.alloc 264 $ \stPtr ->-        B.withByteArray key $ \keyPtr -> c_rc4_init keyPtr (fromIntegral $ B.length key) (castPtr stPtr)-    return $ State st+initialize key+    | B.length key < 1 = error "Crypto.Cipher.RC4: the key must not be empty"+    | otherwise = unsafeDoIO $ do+        -- only the first 256 bytes are used, and the C takes a uint32_t+        st <- B.alloc 264 $ \stPtr ->+            B.withByteArray key $ \keyPtr ->+                c_rc4_init keyPtr (fromIntegral $ min 256 $ B.length key) (castPtr stPtr)+        return $ State st  -- | generate the next len bytes of the rc4 stream without combining -- it to anything.
Crypto/Cipher/Salsa.hs view
@@ -38,14 +38,16 @@     -> key     -- ^ the key (128 or 256 bits)     -> nonce-    -- ^ the nonce (64 or 96 bits)+    -- ^ the nonce (64 bits)     -> State     -- ^ the initial Salsa state initialize nbRounds key nonce     | kLen `notElem` [16, 32] =         error "Salsa: key length should be 128 or 256 bits"-    | nonceLen `notElem` [8, 12] =-        error "Salsa: nonce length should be 64 or 96 bits"+    -- a 96-bit nonce used to be taken, its last word starting the block+    -- counter, so that nonces one apart shared all but a block of keystream+    | nonceLen /= 8 =+        error "Salsa: nonce length should be 64 bits"     | nbRounds `notElem` [8, 12, 20] = error "Salsa: rounds should be 8, 12 or 20"     | otherwise = unsafeDoIO $ do         stPtr <- B.alloc 132 $ \stPtr ->
Crypto/ECC/Simple/Types.hs view
@@ -58,6 +58,7 @@     SEC_t571r1 (..), ) where +import Crypto.Debug (DebugShow (..)) import Crypto.Internal.Imports import Crypto.Number.Basic (numBits) import Data.Data@@ -106,7 +107,14 @@  -- | ECC Private Number newtype Scalar curve = Scalar Integer-    deriving (Show, Read, Eq, Data, NFData)+    deriving (Read, Eq, Data, NFData)++-- | The number is not shown.  Use 'Crypto.Debug.debugShow' to see it.+instance Show (Scalar curve) where+    showsPrec d _ = showParen (d > 10) $ showString "Scalar <secret>"++instance DebugShow (Scalar curve) where+    debugShow (Scalar s) = showString "Scalar " . showsPrec 11 s $ ""  -- | Define a point on a curve. data Point curve
Crypto/Hash.hs view
@@ -51,7 +51,10 @@ import Crypto.Hash.Types import Crypto.Internal.ByteArray (ByteArrayAccess, allocAndFreezePrim) import qualified Crypto.Internal.ByteArray as B+import Data.Bits (shiftR, unsafeShiftR, (.|.)) import qualified Data.ByteString.Lazy as L+import Data.Int (Int64)+import Data.Word (Word32, Word64) import Foreign.Marshal.Alloc (allocaBytes) import qualified Foreign.Marshal.Utils as FMU import Foreign.Ptr (Ptr, castPtr)@@ -120,6 +123,9 @@ -- order to exclude a variable padding, without leaking the padding length.  The -- begining of the message, never impacted by the padding, should preferably go -- through 'hashUpdate' for better performance.+--+-- An N that is negative or past the end takes the whole bytestring, which must+-- be shorter than 4 GiB less 512 bytes. hashFinalizePrefix     :: forall a ba      . (HashAlgorithmPrefix a, ByteArrayAccess ba)@@ -127,18 +133,32 @@     -> ba     -> Int     -> Digest a-hashFinalizePrefix !c b len = Digest $-    allocAndFreezePrim (hashDigestSize (undefined :: a)) $-        \(dig :: Ptr (Digest a)) -> do-            ((!_) :: B.Bytes) <- B.copy c $ \(ctx :: Ptr (Context a)) ->-                B.withByteArray b $ \d ->-                    hashInternalFinalizePrefix-                        ctx-                        d-                        (fromIntegral $ B.length b)-                        (fromIntegral len)-                        dig-            return ()+hashFinalizePrefix !c b len+    -- the C counts in 32 bits up to the length plus a block and the size bytes+    | (fromIntegral (B.length b) :: Word64) >= 0xfffffe00 =+        error "Crypto.Hash.hashFinalizePrefix: input of 4 GiB - 512 bytes or more"+    | otherwise = Digest $+        allocAndFreezePrim (hashDigestSize (undefined :: a)) $+            \(dig :: Ptr (Digest a)) -> do+                ((!_) :: B.Bytes) <- B.copy c $ \(ctx :: Ptr (Context a)) ->+                    B.withByteArray b $ \d ->+                        hashInternalFinalizePrefix+                            ctx+                            d+                            (fromIntegral $ B.length b)+                            (saturate32 len)+                            dig+                return ()++-- | An Int outside [0, 2^32) as 0xffffffff, which the C takes as the whole+-- buffer; without a branch, as the length is secret.+saturate32 :: Int -> Word32+saturate32 n =+    fromIntegral n64 .|. negate (fromIntegral (outside `unsafeShiftR` 63))+  where+    n64 = fromIntegral n :: Int64+    hi = n64 `shiftR` 32+    outside = fromIntegral (hi .|. negate hi) :: Word64  -- | Initialize a new context for a specified hash algorithm hashInitWith :: HashAlgorithm alg => alg -> Context alg
Crypto/Internal/ByteArray.hs view
@@ -28,7 +28,7 @@ import Data.Bits ((.|.)) import qualified Data.Primitive.ByteArray as Prim import Data.Word (Word32, Word8)-import Foreign.Ptr (Ptr, castPtr)+import Foreign.Ptr (Ptr, castPtr, plusPtr) import Foreign.Storable (peekByteOff)  import Crypto.Internal.Compat (unsafeDoIO)@@ -115,7 +115,12 @@     alloc n $ \pd ->         withByteArray a $ \pa ->             withByteArray b $ \pb ->-                c_memxor pd pa pb (fromIntegral n)+                inCLengths n $ \off m ->+                    c_memxor+                        (pd `plusPtr` off)+                        (pa `plusPtr` off)+                        (pb `plusPtr` off)+                        (fromIntegral m)   where     n = min (Data.ByteArray.length a) (Data.ByteArray.length b) 
Crypto/Internal/Nat.hs view
@@ -17,10 +17,19 @@ import           GHC.TypeLits  byteLen :: (KnownNat bitlen, Num a) => proxy bitlen -> a-byteLen d = fromInteger ((natVal d + 7) `div` 8)+byteLen d = fromInteger ((checkedNatVal d + 7) `div` 8)  integralNatVal :: (KnownNat bitlen, Num a) => proxy bitlen -> a-integralNatVal = fromInteger . natVal+integralNatVal = fromInteger . checkedNatVal++-- The C takes a bit length as uint32_t; a larger one used to wrap, and the+-- C then wrote less than the buffer sized from the unwrapped value.+checkedNatVal :: KnownNat bitlen => proxy bitlen -> Integer+checkedNatVal d+    | n > 0xffffffff = error ("Crypto.Internal.Nat: " ++ show n ++ " bits is more than 2^32 - 1")+    | otherwise = n+  where+    n = natVal d  type family IsLE (bitlen :: Nat) (n :: Nat) (c :: Bool) where     IsLE _ _ 'True  = 'True
Crypto/KDF/BCrypt.hs view
@@ -62,7 +62,7 @@ ) where -import Control.Monad (unless, when)+import Control.Monad (unless) import Crypto.Cipher.Blowfish.Primitive (bcryptHash) import Crypto.Error import Crypto.Random (MonadRandom, getRandomBytes)@@ -220,7 +220,12 @@     unless         (version == 'b' || version == 'a' || version == 'y')         (Left ("Unsupported minor version: " ++ [version]))-    when (costTens > 3 || cost > 31 || cost < 4) (Left "Invalid bcrypt cost")+    unless+        ( all (isDigit . chr . fromIntegral . B.index bc) [4, 5]+            && cost >= 4+            && cost <= 31+        )+        (Left "Invalid bcrypt cost")     (salt, hash) <- decodeSaltHash (B.drop 7 bc)     return (BCH version cost salt hash)   where
Crypto/KDF/PBKDF2.hs view
@@ -78,10 +78,19 @@  -- | 'validateParameters', and an iteration count the C can take: it is a -- @uint32_t@ there, so 2^32 + 1 would silently run once.-validateFastParameters :: Parameters -> Maybe CryptoError-validateFastParameters params+validateFastParameters :: Int -> Parameters -> Maybe CryptoError+validateFastParameters hLen params     | toInteger (iterCounts params) > toInteger (maxBound :: Word32) =         Just CryptoError_ParameterInvalid+    | otherwise = validateLength hLen params++-- | 'validateParameters', and RFC 8018's limit of (2^32 - 1) blocks: the+-- block index is 32 bits, so a longer key would repeat its first blocks.+validateLength :: Int -> Parameters -> Maybe CryptoError+validateLength hLen params+    | toInteger (outputLength params)+        > toInteger (maxBound :: Word32) * toInteger hLen =+        Just CryptoError_ParameterInvalid     | otherwise = validateParameters params  -- | generate the pbkdf2 key derivation function from the output@@ -109,7 +118,7 @@     -> salt     -> CryptoFailable ba tryGenerate prf params password salt-    | Just err <- validateParameters params = CryptoFailed err+    | Just err <- validateLength hLen params = CryptoFailed err     | otherwise = CryptoPassed $ B.allocAndFreeze (outputLength params) $ \p -> do         memSet p 0 (outputLength params)         loop 1 (outputLength params) p@@ -180,7 +189,7 @@     -> salt     -> CryptoFailable out tryFastPBKDF2_SHA1 params password salt-    | Just err <- validateFastParameters params = CryptoFailed err+    | Just err <- validateFastParameters 20 params = CryptoFailed err     | otherwise = CryptoPassed $ B.allocAndFreeze (outputLength params) $ \outPtr ->         B.withByteArray password $ \passPtr ->             B.withByteArray salt $ \saltPtr ->@@ -216,7 +225,7 @@     -> salt     -> CryptoFailable out tryFastPBKDF2_SHA256 params password salt-    | Just err <- validateFastParameters params = CryptoFailed err+    | Just err <- validateFastParameters 32 params = CryptoFailed err     | otherwise = CryptoPassed $ B.allocAndFreeze (outputLength params) $ \outPtr ->         B.withByteArray password $ \passPtr ->             B.withByteArray salt $ \saltPtr ->@@ -252,7 +261,7 @@     -> salt     -> CryptoFailable out tryFastPBKDF2_SHA512 params password salt-    | Just err <- validateFastParameters params = CryptoFailed err+    | Just err <- validateFastParameters 64 params = CryptoFailed err     | otherwise = CryptoPassed $ B.allocAndFreeze (outputLength params) $ \outPtr ->         B.withByteArray password $ \passPtr ->             B.withByteArray salt $ \saltPtr ->
Crypto/KDF/Scrypt.hs view
@@ -34,7 +34,7 @@     { n :: Word64     -- ^ Cpu/Memory cost ratio. must be a power of 2 greater than 1. also known as N.     , r :: Int-    -- ^ Must be positive and satisfy r * p < 2^30+    -- ^ Must be positive, below 2^26, and satisfy r * p < 2^30     , p :: Int     -- ^ Must be positive and satisfy r * p < 2^30     , outputLength :: Int@@ -101,6 +101,8 @@     n params >= 2         && popCount (n params) == 1         && r' >= 1+        -- the C indexes a block of 32 * r words with int and uint32_t+        && r' < 0x4000000         && p' >= 1         && r' * p' < 0x40000000         && 128 * r' * n' <= maxInt
Crypto/MAC/KeyedBlake2.hs view
@@ -52,20 +52,30 @@ newtype Context a = Context (H.Context a)  -- | Initialize a new incremental keyed Blake2 context with the supplied key.+--+-- The key may be up to 64 bytes for Blake2b and Blake2bp, and up to 32 bytes+-- for Blake2s and Blake2sp, whatever the digest size (RFC 7693).  A longer key+-- is an error. initialize     :: forall a key      . (HashBlake2 a, ByteArrayAccess key)     => key -> Context a-initialize k = Context $ H.Context $ B.allocAndFreeze ctxSz performInit+initialize k+    -- it used to be cut to the digest size, so keys that agreed that far+    -- gave the same MAC, and a longer key was not the RFC's+    | B.length k > maxKeySz =+        error $+            "Crypto.MAC.KeyedBlake2: key longer than "+                ++ show maxKeySz+                ++ " bytes"+    | otherwise = Context $ H.Context $ B.allocAndFreeze ctxSz performInit   where     ctxSz = H.hashInternalContextSize (undefined :: a)-    digestSz = H.hashDigestSize (undefined :: a)-    -- cap the number of key bytes at digestSz,-    -- since that's the maximal key size-    keyByteLen = min (B.length k) digestSz+    -- the BLAKE2 maximal key size is half its block size: 64 or 32 bytes+    maxKeySz = H.hashBlockSize (undefined :: a) `div` 2     performInit :: Ptr (H.Context a) -> IO ()     performInit ptr = B.withByteArray k $-        \keyPtr -> blake2InternalKeyedInit ptr keyPtr (fromIntegral keyByteLen)+        \keyPtr -> blake2InternalKeyedInit ptr keyPtr (fromIntegral (B.length k))  -- | Incrementally update a keyed Blake2 context. update :: (HashBlake2 a, ByteArrayAccess ba) => Context a -> ba -> Context a
Crypto/Number/Generate.hs view
@@ -60,6 +60,8 @@             Nothing -> return ()             Just SetHighest -> p0 |= (1 `shiftL` bit)             Just SetTwoHighest+                -- one bit has no second highest, and p1 is past the buffer+                | bits == 1 -> p0 |= 0x1                 | bit == 0 -> do                     p0 $= 0x1                     p1 |= 0x80
Crypto/PubKey/DSA.hs view
@@ -262,6 +262,9 @@ verifyDigest pk (Signature r s) digest     -- Reject the signature if either 0 < r < q or 0 < s < q is not satisfied.     | r <= 0 || r >= q || s <= 0 || s >= q = False+    -- the parameters come from the signer; a modulus below 2 is no group,+    -- and p = 0 used to raise divide by zero rather than answer False+    | p < 2 = False     -- s is invertible for every 0 < s < q when q is prime, but the parameters     -- arrive with the public key and a composite q admits an s that is not     | otherwise = maybe False (r ==) v
Crypto/PubKey/ECC/ECDSA.hs view
@@ -247,10 +247,14 @@     => Curve -> ExtendedSignature -> Digest hash -> Maybe PublicKey recoverDigest curve (ExtendedSignature i p (Signature r s)) digest = do     let CurveCommon _ _ g n _ = common_curve curve+    -- SEC 1 4.1.6 takes r and s in [1, n-1], as verify does+    guard (r > 0 && r < n && s > 0 && s < n && i >= 0)     let z = dsaTruncHashDigest digest n     w <- inverse r n     c <- pointCompose curve i r p-    pure $ PublicKey curve $ pointAddTwoMuls curve (s * w) c (negate $ z * w) g+    let q = pointAddTwoMuls curve (s * w) c (negate $ z * w) g+    guard (not (isPointAtInfinity q))+    pure $ PublicKey curve q  -- | Recover the public key from an extended signature and a message. recover
Crypto/PubKey/ECC/P256.hs view
@@ -234,9 +234,14 @@ -- Scalar methods ------------------------------------------------------------------------ --- | Generate a randomly generated new scalar+-- | Generate a randomly generated new scalar, uniform in [1, n - 1]+--+-- 256 random bits are drawn again until they fall in that range, rather than+-- being reduced modulo n, which would favour the small values. scalarGenerate :: MonadRandom randomly => randomly Scalar-scalarGenerate = unwrap . scalarFromBinary . witness <$> getRandomBytes 32+scalarGenerate = do+    s <- unwrap . scalarFromBinary . witness <$> getRandomBytes 32+    if scalarIsZero s || scalarCmp s scalarN /= LT then scalarGenerate else return s   where     unwrap (CryptoFailed _) = error "scalarGenerate: assumption failed"     unwrap (CryptoPassed s) = s
Crypto/PubKey/ECC/Prim.hs view
@@ -497,6 +497,8 @@     let x = residue + index * n     y <- case curve of         CurveFP (CurvePrime p _) -> do+            -- x is a field element; one at or past p names another point+            if x < 0 || x >= p then Nothing else Just ()             z <- squareRoot p $ x ^ (3 :: Int) + a * x + b             pure $ if odd z == parity then z else p - z         CurveF2m (CurveBinary fx _) | x == 0 -> pure $ sqrtF2m fx b
Crypto/PubKey/ElGamal.hs view
@@ -155,12 +155,16 @@  -- | decrypt message ----- @c1@ must be a unit modulo @p@; a ciphertext whose first component is zero--- or out of range is rejected rather than raising.+-- @c1@ must lie in @[2, p-2]@; a ciphertext whose first component is zero or+-- out of range is rejected rather than raising.  @1@ and @p-1@ are refused as+-- 'encryptWith' refuses them for a public number: @(p-1)^a@ is @1@ or @-1@ as+-- @a@ is even or odd, so decrypting @(p-1, c2)@ tells the parity of the+-- private number.  With a modulus that is not a safe prime, other elements of+-- small order remain, which only a check of the subgroup would catch. decrypt     :: Params -> PrivateNumber -> (Integer, Integer) -> CryptoFailable Integer decrypt (Params p _ _) (PrivateNumber a) (c1, c2)-    | c1 <= 0 || c1 >= p = CryptoFailed CryptoError_ParameterInvalid+    | not (validPublic p c1) = CryptoFailed CryptoError_ParameterInvalid     | c2 < 0 || c2 >= p = CryptoFailed CryptoError_ParameterInvalid     | otherwise = case inverseSafe s p of         Nothing -> CryptoFailed CryptoError_ParameterInvalid
Crypto/PubKey/RSA.hs view
@@ -141,9 +141,12 @@     => Int     -- ^ size in bytes     -> Integer-    -- ^ RSA public exponent @e@+    -- ^ RSA public exponent @e@, odd and at least 3 (65537 is the usual one)     -> m (PublicKey, PrivateKey)-generate size e = loop+generate size e+    -- phi is even, so such an e has no inverse and the loop never ended+    | e < 3 || even e = error "Crypto.PubKey.RSA.generate: e must be odd and at least 3"+    | otherwise = loop   where     loop = do         -- loop until we find a valid key pair given e
Crypto/PubKey/RSA/PSS.hs view
@@ -276,6 +276,8 @@ verifyDigest params pk digest s     | B.length s /= k = False     | os2ip s >= public_n pk = False+    -- RFC 8017 9.1.2 step 3; an empty em (n = 1) used to make B.last raise+    | emLen < hashLen + pssSaltLength params + 2 = False     | B.any (/= 0) pre = False     | B.any (\x -> x .&. topBits /= 0) (B.take 1 maskedDB) = False     | B.last em /= pssTrailerField params = False
Crypto/PubKey/RSA/Types.hs view
@@ -54,7 +54,15 @@ -- Use a blinder once.  'Crypto.PubKey.RSA.generateBlinder' makes a fresh one; -- carrying one across operations is not what it is for. data Blinder = Blinder !Integer !Integer-    deriving (Show, Eq)+    deriving (Eq)++-- | Hidden: the blinder masks the private-key input, so it is as secret as+-- that input.  Use 'Crypto.Debug.debugShow' to see it.+instance Show Blinder where+    showsPrec d _ = showParen (d > 10) $ showString "Blinder <secret> <secret>"++instance DebugShow Blinder where+    debugShow (Blinder r rm1) = "Blinder " ++ showsPrec 11 r (' ' : showsPrec 11 rm1 "")  -- | error possible during encryption, decryption or signing. data Error
Crypto/Random/Entropy.hs view
@@ -38,5 +38,11 @@         return $ maybe rest (: rest) m  -- | Get some entropy from the system source of entropy+--+-- A negative length is an error.  @alloc@ would make an empty buffer of it,+-- and the length itself, narrowed for the system call, could come out+-- positive and be written into that buffer. getEntropy :: ByteArray byteArray => Int -> IO byteArray-getEntropy n = B.alloc n (replenish n openedBackends)+getEntropy n+    | n < 0 = error "Crypto.Random.Entropy: negative length"+    | otherwise = B.alloc n (replenish n openedBackends)
Crypto/Random/Entropy/Unsafe.hs view
@@ -23,6 +23,8 @@ -- and 'EntropyShort' when three passes over the backends still leave the -- buffer unfilled. replenish :: Int -> [EntropyBackend] -> Ptr Word8 -> IO ()+replenish n _ _+    | n < 0 = error "Crypto.Random.Entropy.Unsafe.replenish: negative length" replenish _ [] _ = throwIO NoEntropySource replenish poolSize backends ptr = loop 0 backends ptr poolSize   where
Crypto/Random/Entropy/Windows.hs view
@@ -17,7 +17,7 @@ import Data.Int (Int32) import Data.Word import Foreign.C.String (CString, withCString)-import Foreign.Ptr (Ptr, nullPtr)+import Foreign.Ptr (Ptr, nullPtr, plusPtr) import Foreign.Marshal.Alloc (alloca) import Foreign.Marshal.Utils (toBool) import Foreign.Storable (peek)@@ -90,10 +90,17 @@             then Just `fmap` peek handlePtr             else return Nothing +-- The length is a DWORD, so a request of 4 GiB or more goes in pieces;+-- returns how many bytes were filled. cryptGenRandom :: CryptCtx -> Ptr Word8 -> Int -> IO Int-cryptGenRandom h buf n = do-    success <- toBool `fmap` c_cryptGenRandom h (fromIntegral n) buf-    return $ if success then n else 0+cryptGenRandom h buf n = go buf (max 0 n)+  where+    go p left+        | left == 0 = return n+        | otherwise = do+            let m = min left 0x40000000+            success <- toBool `fmap` c_cryptGenRandom h (fromIntegral m) p+            if success then go (p `plusPtr` m) (left - m) else return (n - left)  cryptReleaseCtx :: CryptCtx -> IO () cryptReleaseCtx h = do
Crypto/Random/EntropyPool.hs view
@@ -33,10 +33,14 @@ -- While you can create as many entropy pools as you want, -- the pool can be shared between multiples RNGs. createEntropyPoolWith :: Int -> [EntropyBackend] -> IO EntropyPool-createEntropyPoolWith poolSize backends = do-    m <- newMVar 0-    sm <- B.alloc poolSize (replenish poolSize backends)-    return $ EntropyPool backends m sm+createEntropyPoolWith poolSize backends+    -- an empty pool can never hand out a byte; drawing from one looped forever+    | poolSize <= 0 =+        error "Crypto.Random.EntropyPool: the pool size must be positive"+    | otherwise = do+        m <- newMVar 0+        sm <- B.alloc poolSize (replenish poolSize backends)+        return $ EntropyPool backends m sm  -- | Create a new entropy pool with a default size. --@@ -67,5 +71,9 @@             copyLoop (d `plusPtr` m) s (wrappedPos + m) (left - m)  -- | Grab a chunk of entropy from the entropy pool.+--+-- A negative length is an error; it used to reach a copy of negative size. getEntropyFrom :: ByteArray byteArray => EntropyPool -> Int -> IO byteArray-getEntropyFrom pool n = B.alloc n (getEntropyPtr pool n)+getEntropyFrom pool n+    | n < 0 = error "Crypto.Random.EntropyPool: negative length"+    | otherwise = B.alloc n (getEntropyPtr pool n)
cbits/crypton_aes.c view
@@ -739,6 +739,8 @@  /* Crypto.Cipher.AES.Primitive reads length_input at this offset */ typedef char crypton_gcm_length_input_offset[offsetof(aes_gcm, length_input) == 312 ? 1 : -1];+/* Crypto.Cipher.AES.Primitive allocates sizeOCB bytes */+typedef char crypton_ocb_size[sizeof(aes_ocb) <= 176 ? 1 : -1];  void crypton_aes_gcm_aad(aes_gcm *gcm, uint8_t *input, uint32_t length) {@@ -1123,10 +1125,11 @@ 	d->b[15] = (s->b[15] << 1) ^ ((tmp >> 7) * 0x87); } -static void ocb_get_L_i(block128 *l, block128 *lis, unsigned int i)+static void ocb_get_L_i(block128 *l, block128 *lis, uint64_t n) { #define L_CACHED 4-	i = bitfn_ntz(i);+	unsigned int i = (uint32_t) n ? bitfn_ntz((uint32_t) n)+	                              : 32 + bitfn_ntz((uint32_t) (n >> 32)); 	if (i < L_CACHED) { 		block128_copy(l, &lis[i]); 	} else {@@ -1208,6 +1211,8 @@ 	block128_zero(&ocb->sum_aad); 	block128_zero(&ocb->sum_enc); 	block128_zero(&ocb->offset_aad);+	ocb->blocks_aad = 0;+	ocb->blocks_enc = 0; }  void crypton_aes_ocb_aad(aes_ocb *ocb, aes_key *key, uint8_t *input, uint32_t length)@@ -1215,8 +1220,10 @@ 	block128 tmp; 	block128 buf[OCB_WAY]; 	uint32_t blocks = length / 16;-	unsigned int i = 1, j;+	uint64_t i = ocb->blocks_aad + 1;+	unsigned int j; +	ocb->blocks_aad += blocks; 	for (; blocks >= OCB_WAY; blocks -= OCB_WAY, input += 16 * OCB_WAY) { 		for (j = 0; j < OCB_WAY; j++, i++) { 			ocb_get_L_i(&tmp, ocb->li, i);@@ -1551,8 +1558,10 @@ 	block128 tmp, pad; 	block128 offsets[OCB_WAY], buf[OCB_WAY]; 	uint32_t blocks = length / 16;-	unsigned int i = 1, j;+	uint64_t i = ocb->blocks_enc + 1;+	unsigned int j; +	ocb->blocks_enc += blocks; 	for (; blocks >= OCB_WAY; 	     blocks -= OCB_WAY, input += 16 * OCB_WAY, output += 16 * OCB_WAY) { 		for (j = 0; j < OCB_WAY; j++, i++) {
cbits/crypton_aes.h view
@@ -125,6 +125,10 @@ 	block128 lstar; 	block128 ldollar; 	block128 li[4];+	/* blocks hashed or encrypted so far, so that a call carries on the+	 * index where the previous one stopped */+	uint64_t blocks_aad;+	uint64_t blocks_enc; } aes_ocb;  /* size = 17*16= 272 */
cbits/crypton_blake2b.c view
@@ -5,9 +5,14 @@ 	_crypton_blake2b_init(ctx, hashlen / 8); } -void crypton_blake2b_init_key(blake2b_ctx *ctx, uint32_t hashlen, const uint8_t *key, size_t keylen)+void crypton_blake2b_init_key(blake2b_ctx *ctx, uint32_t hashlen, const uint8_t *key, uint32_t keylen) {-	_crypton_blake2b_init_key(ctx, hashlen / 8, (const void *) key, keylen);+	/* RFC 7693: an empty key is the unkeyed hash; init_key refuses it+	 * and would leave ctx uninitialised */+	if (keylen == 0)+		_crypton_blake2b_init(ctx, hashlen / 8);+	else+		_crypton_blake2b_init_key(ctx, hashlen / 8, (const void *) key, keylen); }  void crypton_blake2b_update(blake2b_ctx *ctx, const uint8_t *data, uint32_t len)
cbits/crypton_blake2b.h view
@@ -6,7 +6,7 @@ typedef blake2b_state blake2b_ctx;  void crypton_blake2b_init(blake2b_ctx *ctx, uint32_t hashlen);-void crypton_blake2b_init_key(blake2b_ctx *ctx, uint32_t hashlen, const uint8_t *key, size_t keylen);+void crypton_blake2b_init_key(blake2b_ctx *ctx, uint32_t hashlen, const uint8_t *key, uint32_t keylen); void crypton_blake2b_update(blake2b_ctx *ctx, const uint8_t *data, uint32_t len); void crypton_blake2b_finalize(blake2b_ctx *ctx, uint32_t hashlen, uint8_t *out); 
cbits/crypton_blake2bp.c view
@@ -5,9 +5,14 @@ 	_crypton_blake2bp_init(ctx, hashlen / 8); } -void crypton_blake2bp_init_key(blake2bp_ctx *ctx, uint32_t hashlen, const uint8_t *key, size_t keylen)+void crypton_blake2bp_init_key(blake2bp_ctx *ctx, uint32_t hashlen, const uint8_t *key, uint32_t keylen) {-	_crypton_blake2bp_init_key(ctx, hashlen / 8, (const void *) key, keylen);+	/* RFC 7693: an empty key is the unkeyed hash; init_key refuses it+	 * and would leave ctx uninitialised */+	if (keylen == 0)+		_crypton_blake2bp_init(ctx, hashlen / 8);+	else+		_crypton_blake2bp_init_key(ctx, hashlen / 8, (const void *) key, keylen); }  void crypton_blake2bp_update(blake2bp_ctx *ctx, const uint8_t *data, uint32_t len)
cbits/crypton_blake2bp.h view
@@ -6,7 +6,7 @@ typedef blake2bp_state blake2bp_ctx;  void crypton_blake2bp_init(blake2bp_ctx *ctx, uint32_t hashlen);-void crypton_blake2bp_init_key(blake2bp_ctx *ctx, uint32_t hashlen, const uint8_t *key, size_t keylen);+void crypton_blake2bp_init_key(blake2bp_ctx *ctx, uint32_t hashlen, const uint8_t *key, uint32_t keylen); void crypton_blake2bp_update(blake2bp_ctx *ctx, const uint8_t *data, uint32_t len); void crypton_blake2bp_finalize(blake2bp_ctx *ctx, uint32_t hashlen, uint8_t *out); 
cbits/crypton_blake2s.c view
@@ -5,9 +5,14 @@ 	_crypton_blake2s_init(ctx, hashlen / 8); } -void crypton_blake2s_init_key(blake2s_ctx *ctx, uint32_t hashlen, const uint8_t *key, size_t keylen)+void crypton_blake2s_init_key(blake2s_ctx *ctx, uint32_t hashlen, const uint8_t *key, uint32_t keylen) {-	_crypton_blake2s_init_key(ctx, hashlen / 8, (const void *) key, keylen);+	/* RFC 7693: an empty key is the unkeyed hash; init_key refuses it+	 * and would leave ctx uninitialised */+	if (keylen == 0)+		_crypton_blake2s_init(ctx, hashlen / 8);+	else+		_crypton_blake2s_init_key(ctx, hashlen / 8, (const void *) key, keylen); }  void crypton_blake2s_update(blake2s_ctx *ctx, const uint8_t *data, uint32_t len)
cbits/crypton_blake2s.h view
@@ -6,7 +6,7 @@ typedef blake2s_state blake2s_ctx;  void crypton_blake2s_init(blake2s_ctx *ctx, uint32_t hashlen);-void crypton_blake2s_init_key(blake2s_ctx *ctx, uint32_t hashlen, const uint8_t *key, size_t keylen);+void crypton_blake2s_init_key(blake2s_ctx *ctx, uint32_t hashlen, const uint8_t *key, uint32_t keylen); void crypton_blake2s_update(blake2s_ctx *ctx, const uint8_t *data, uint32_t len); void crypton_blake2s_finalize(blake2s_ctx *ctx, uint32_t hashlen, uint8_t *out); 
cbits/crypton_blake2sp.c view
@@ -5,9 +5,14 @@ 	_crypton_blake2sp_init(ctx, hashlen / 8); } -void crypton_blake2sp_init_key(blake2sp_ctx *ctx, uint32_t hashlen, const uint8_t *key, size_t keylen)+void crypton_blake2sp_init_key(blake2sp_ctx *ctx, uint32_t hashlen, const uint8_t *key, uint32_t keylen) {-	_crypton_blake2sp_init_key(ctx, hashlen / 8, (const void *) key, keylen);+	/* RFC 7693: an empty key is the unkeyed hash; init_key refuses it+	 * and would leave ctx uninitialised */+	if (keylen == 0)+		_crypton_blake2sp_init(ctx, hashlen / 8);+	else+		_crypton_blake2sp_init_key(ctx, hashlen / 8, (const void *) key, keylen); }  void crypton_blake2sp_update(blake2sp_ctx *ctx, const uint8_t *data, uint32_t len)
cbits/crypton_blake2sp.h view
@@ -6,7 +6,7 @@ typedef blake2sp_state blake2sp_ctx;  void crypton_blake2sp_init(blake2sp_ctx *ctx, uint32_t hashlen);-void crypton_blake2sp_init_key(blake2sp_ctx *ctx, uint32_t hashlen, const uint8_t *key, size_t keylen);+void crypton_blake2sp_init_key(blake2sp_ctx *ctx, uint32_t hashlen, const uint8_t *key, uint32_t keylen); void crypton_blake2sp_update(blake2sp_ctx *ctx, const uint8_t *data, uint32_t len); void crypton_blake2sp_finalize(blake2sp_ctx *ctx, uint32_t hashlen, uint8_t *out); 
cbits/crypton_f2m.c view
@@ -79,7 +79,10 @@ 		} } -#if defined(__aarch64__) && (defined(__GNUC__) || defined(__clang__))+/* Without the attributes PMULL is reachable only where the baseline has it. */+#if defined(__aarch64__) && (defined(__GNUC__) || defined(__clang__)) && \+    (defined(WITH_TARGET_ATTRIBUTES) || defined(__ARM_FEATURE_CRYPTO) || \+     defined(__ARM_FEATURE_AES)) #define HAVE_PMULL 1 #include <arm_neon.h> 
cbits/crypton_pbkdf2.c view
@@ -216,7 +216,11 @@     HMAC_INIT(_name)(&ctx, pw, npw);                                          \                                                                               \     /* How many blocks do we need? */                                         \-    uint32_t blocks_needed = (uint32_t)(nout + _hashsz - 1) / _hashsz;        \+    /* divide before narrowing; the caller keeps this below 2^32 */          \+    uint64_t blocks64 = ((uint64_t) nout + _hashsz - 1) / _hashsz;           \+    if (blocks64 > UINT32_MAX)                                                \+      return;                                                                 \+    uint32_t blocks_needed = (uint32_t) blocks64;                             \                                                                               \     for (uint32_t counter = 1; counter <= blocks_needed; counter++)           \     {                                                                         \
cbits/crypton_rc4.c view
@@ -26,6 +26,8 @@ { 	uint32_t i, j; 	memset(ctx, 0, sizeof(struct rc4_ctx));+	if (keylen == 0) /* key[i % 0]; the Haskell side refuses an empty key */+		return;  	/* initialize context */ 	for (i = 0; i < 256; i++)
cbits/crypton_salsa.c view
@@ -140,15 +140,12 @@  	st->d[9] = 0; 	switch (ivlen) {+	/* a 12-byte nonce put its last word into the counter, d[8] */ 	case 8: 		st->d[6] = load_le32(iv + 0); 		st->d[7] = load_le32(iv + 4); 		st->d[8] = 0; 		break;-	case 12:-		st->d[6] = load_le32(iv + 0);-		st->d[7] = load_le32(iv + 4);-		st->d[8] = load_le32(iv + 8); 	default: 		return; 	}
cbits/crypton_scrypt.c view
@@ -32,7 +32,7 @@  static void blockmix_salsa8(uint32_t *in, uint32_t *out, uint32_t *X, const uint32_t r) {-	int i;+	size_t i;  	array_copy32(X, &in[(2 * r - 1) * 16], 16); @@ -56,8 +56,8 @@ 	uint32_t *Y = &XY[32 * r]; 	uint32_t *Z = &XY[64 * r]; 	uint64_t i, j;-	int k;-	const int r32 = 32*r;+	size_t k;+	const size_t r32 = (size_t) 32 * r; /* the caller keeps r below 2^26 */  	for (k = 0; k < r32; k++) 		X[k] = load_le32_aligned(&B[4 * k]);
cbits/crypton_sha3.c view
@@ -70,7 +70,8 @@ } #endif -#if defined(WITH_ARMV8_SHA3_ASM) && !defined(__AARCH64EB__)+#if defined(WITH_ARMV8_SHA3_ASM) && defined(WITH_ARMV8_SHA3) && \+    !defined(__AARCH64EB__) /*  * Keccak from CRYPTOGAMS, in cbits/asm/keccak1600-armv8-*.S, which takes a  * run of blocks rather than one at a time and schedules the instructions
cbits/crypton_skein256.c view
@@ -170,7 +170,8 @@ { 	uint32_t outsize; 	uint64_t x[4];-	int i, j, n;+	uint32_t i;+	int j, n;  	ctx->t1 |= FLAG_FINAL; 	/* if buf is not complete pad with 0 bytes */@@ -181,7 +182,7 @@ 	memset(ctx->buf, '\0', 32);  	/* make sure we have a 8 bit up rounded value */-	outsize = (hashlen + 7) >> 3;+	outsize = (hashlen >> 3) + ((hashlen & 7) != 0); /* no wrap at 2^32 - 7 */  	/* backup h[0--4] */ 	for (j = 0; j < 4; j++)
cbits/crypton_skein512.c view
@@ -185,7 +185,8 @@ { 	uint32_t outsize; 	uint64_t x[8];-	int i, j, n;+	uint32_t i;+	int j, n;  	ctx->t1 |= FLAG_FINAL; 	/* if buf is not complete pad with 0 bytes */@@ -196,7 +197,7 @@ 	memset(ctx->buf, '\0', 64);  	/* make sure we have a 8 bit rounded value */-	outsize = (hashlen + 7) >> 3;+	outsize = (hashlen >> 3) + ((hashlen & 7) != 0); /* no wrap at 2^32 - 7 */  	/* backup h[0--7] */ 	for (j = 0; j < 8; j++)
cbits/crypton_sysdrg.c view
@@ -118,7 +118,8 @@ 	 * as a second source when it is the same one twice. 	 */ 	got = crypton_sysrandom_available() ? crypton_sysrandom_bytes(buf, 64) : 0;-	if (got <= 0) {+	/* all 64 or nothing: a short read is a call that failed part way */+	if (got != 64) { 		/* Nothing else here is a seed on its own, so there is nothing to 		 * go on with: return before drawing anything that would only be 		 * thrown away. */
cbits/crypton_whirlpool.c view
@@ -861,8 +861,9 @@ 	   | 	   bufferPos 	   */-	int sourceBits   = sourceBytes * 8;-	int sourcePos    = 0; /* index of leftmost source uint8_t containing data (1 to 8 bits). */+	/* 64-bit: sourceBytes * 8 overflows an int from 256 MiB on */+	int64_t sourceBits = (int64_t) sourceBytes * 8;+	size_t sourcePos   = 0; /* index of leftmost source uint8_t containing data (1 to 8 bits). */ 	int sourceGap    = (8 - ((int)sourceBits & 7)) & 7; /* space on source[sourcePos]. */ 	int bufferRem    = ctx->bufferBits & 7; /* occupied bits on buffer[bufferPos]. */ 	int i;
crypton.cabal view
@@ -1,6 +1,6 @@ cabal-version:      3.0 name:               crypton-version:            2.2.6+version:            2.2.7 -- crypton's own code is BSD-3-Clause.  The parts of -- cbits/aes/gcm_fused_x86.c that follow picotls's fusion are MIT, and the -- vendored s2n-bignum assembly in cbits/s2n is taken under ISC, and the@@ -249,7 +249,7 @@  flag use_target_attributes     description:-        use GCC / clang function attributes instead of global target options.+        use GCC / clang function attributes for the code that needs instruction set extensions. Turned off, that code is left out and the portable C is used instead.      manual:      True @@ -549,17 +549,18 @@     -- runtime check; i386 keeps the scalar code.     if arch(x86_64)         cc-options:-            -DWITH_X86_SSE2 -DWITH_X86_AVX2 -DWITH_X86_SHA_NI+            -DWITH_X86_SSE2 -DWITH_X86_AVX2         c-sources:             cbits/chacha_avx2.c             cbits/chacha_sse2.c-            cbits/sha1_x86.c -        -- The SHA extensions are not part of the baseline, so without the-        -- attributes this raises it for every file, as the AES-NI and-        -- AArch64 paths do.-        if !flag(use_target_attributes)-            cc-options: -msha -msse4.1 -mssse3+        -- The SHA extensions are not part of the baseline.  Without the+        -- attributes the only way to reach them is -msha for the whole+        -- component, which lets the compiler emit them in every file, so+        -- the path is left out instead.+        if flag(use_target_attributes)+            cc-options: -DWITH_X86_SHA_NI+            c-sources:  cbits/sha1_x86.c          -- Poly1305, ChaCha20 and the SHA-2 pair from CRYPTOGAMS,         -- hand-scheduled.  Poly1305@@ -766,12 +767,14 @@         -- P-256 and the rest -- and gcc would vectorise code that asks for         -- no such thing, with nothing to check at runtime.  The backends'         -- own AVX2 is all in the .S.  AArch64 needs nothing beyond the-        -- baseline for the arithmetic, and takes the armv8.4 Keccak from-        -- the -march the block below already sets.+        -- baseline for the arithmetic, and takes the armv8.4 Keccak only+        -- where the compiler's own baseline has SHA-3, as on Apple's.         if arch(x86_64)             asm-options: -mavx2 -mbmi2 -    if (flag(support_aesni) && arch(aarch64))+    -- Without the attributes, as for SHA-NI above: -march for the whole+    -- component would let the compiler emit the extensions anywhere.+    if ((flag(support_aesni) && flag(use_target_attributes)) && arch(aarch64))         cc-options: -DWITH_ARMV8_CRYPTO         c-sources:             cbits/aes/generic.c@@ -779,9 +782,6 @@             cbits/aes/armv8.c             cbits/crypton_aes.c -        if !flag(use_target_attributes)-            cc-options: -march=armv8-a+crypto-     -- The same instructions, reached from AArch32.  cbits/aes/armv8.c needs     -- nothing changed to compile here: every intrinsic it uses exists in both     -- execution states, including the PMULL2 it takes through@@ -791,7 +791,7 @@     -- AT_HWCAP2 -- which cbits/crypton_cpu.c now asks for.     --     -- -mfpu is passed whatever use_target_attributes says, unlike the branch-    -- above.  AArch32 names an FPU rather than an architecture extension and+    -- above, which is left out without it.  AArch32 names an FPU rather than an architecture extension and     -- the two compilers spell the function attribute for it differently; a     -- global option is safe here, since a compiler emits these instructions     -- where an intrinsic asks for them and nowhere else.@@ -829,22 +829,20 @@             cbits/asm/ghashp8-ppc-linux64le.S      if arch(aarch64)-        cc-options:-            -DWITH_ARMV8_SHA1 -DWITH_ARMV8_SHA2 -DWITH_ARMV8_SHA3-            -DWITH_ARMV8_SHA512-            -DWITH_ARMV8_NEON-        c-sources:-            cbits/chacha_neon.c-            cbits/sha1_armv8.c-            cbits/sha256_armv8.c-            cbits/sha3_armv8.c-            cbits/sha512_armv8.c+        cc-options: -DWITH_ARMV8_NEON+        c-sources:  cbits/chacha_neon.c -        -- +sha3 covers the SHA-512 instructions as well as the SHA-3 ones,-        -- and leaves the baseline at ARMv8-A: it says what the compiler may-        -- emit where asked, not what the machine is assumed to have.-        if !flag(use_target_attributes)-            cc-options: -march=armv8-a+crypto+sha3+        -- The SHA instructions are extensions; left out without the+        -- attributes, as AES is above.+        if flag(use_target_attributes)+            cc-options:+                -DWITH_ARMV8_SHA1 -DWITH_ARMV8_SHA2 -DWITH_ARMV8_SHA3+                -DWITH_ARMV8_SHA512+            c-sources:+                cbits/sha1_armv8.c+                cbits/sha256_armv8.c+                cbits/sha3_armv8.c+                cbits/sha512_armv8.c          -- ChaCha20, Poly1305 and SHA-256 from CRYPTOGAMS.  ChaCha20 there runs a         -- fifth block through the@@ -892,7 +890,9 @@     -- the table-driven fallback on processors that have had AES-NI since     -- 2010.  The object format still has a say further down, where the GCM     -- assembly is chosen, and there ELF is the default.-    if (flag(support_aesni) && (arch(i386) || arch(x86_64)))+    --+    -- Without the attributes it is left out, as SHA-NI is above.+    if ((flag(support_aesni) && flag(use_target_attributes)) && (arch(i386) || arch(x86_64)))         cc-options: -DWITH_AESNI         c-sources:             cbits/aes/generic.c@@ -900,15 +900,9 @@             cbits/aes/x86ni.c             cbits/crypton_aes.c -        if !flag(use_target_attributes)-            cc-options: -mssse3 -maes-         if flag(support_pclmuldq)             cc-options: -DWITH_PCLMUL -            if !flag(use_target_attributes)-                cc-options: -msse4.1 -mpclmul-             -- AES-GCM from CRYPTOGAMS, which interleaves the counter-mode             -- rounds with the multiplies of the block before at             -- instruction granularity.  The two do not want the same@@ -953,7 +947,7 @@     -- branch had already named every file it names.  Cabal drops the repeats,     -- so nothing was built twice, but the line read as the fallback for a     -- platform with no AES instructions and was not one.-    if !((flag(support_aesni) && (arch(aarch64) || arch(arm))) || (flag(support_aesni) && (arch(i386) || arch(x86_64))) || (flag(support_aesni) && arch(ppc64le)))+    if !((((flag(support_aesni) && flag(use_target_attributes)) && arch(aarch64)) || (flag(support_aesni) && arch(arm))) || ((flag(support_aesni) && flag(use_target_attributes)) && (arch(i386) || arch(x86_64))) || (flag(support_aesni) && arch(ppc64le)))         c-sources:             cbits/aes/generic.c             cbits/aes/gf.c
tests/BlockCipher/AESGCMSIVSpec.hs view
@@ -651,8 +651,8 @@     -> Property encDecTest prx (Key key) iv (ArbitraryBS0_2901 aad) (ArbitraryBS0_2901 input) =     let c = throwCryptoError (cipherInit key) `asProxyTypeOf` prx-        (tag, ciphertext) = encrypt c iv aad input-     in decrypt c iv aad ciphertext tag === Just input+        (tag, sealed) = encrypt c iv aad input+     in decrypt c iv aad sealed tag === Just input  tagKey :: AES128 tagKey = throwCryptoError (cipherInit (B.replicate 16 1 :: ByteString))
tests/BlockCipher/AESSpec.hs view
@@ -385,6 +385,9 @@         it "refuses a sample that does not fit, writing nothing" $ do             withMask (B.length plainSealed - 15) `shouldReturn` Nothing             withMask (-1) `shouldReturn` Nothing+        -- off + 16 used to wrap and pass, and the C read 4 GiB away+        it "refuses an offset near maxBound" $+            withMask (maxBound - 7) `shouldReturn` Nothing   where     run name vs =         it name $@@ -445,6 +448,40 @@          in (GCM.decrypt ctx16 iv16 B.empty (c' `B.append` t') 16 :: Maybe B.ByteString)                 `shouldBe` Nothing +-- OCB fed in chunks must equal one call: each call used to restart the+-- block index, so equal-sized chunks could be swapped under a valid tag+ocbChunkTests :: Spec+ocbChunkTests = describe "OCB in chunks" $ do+    it "equals one call" $+        forM_ splits $ \(as, ms) ->+            enc (chunks as aad) (chunks ms msg) `shouldBe` enc [aad] [msg]+    it "does not accept swapped chunks" $ do+        let three = B.replicate 48 0x5a+            (cs, tag) = enc [] (chunks [16, 16] three)+            swapped = B.concat [B.drop 32 cs, B.take 16 (B.drop 16 cs), B.take 16 cs]+        snd (dec (chunks [16, 16] swapped)) `shouldNotBe` tag+  where+    ctx = throwCryptoError (cipherInit (B.pack [0 .. 15])) :: AES.AES128+    start = throwCryptoError (aeadInit AEAD_OCB ctx (B.pack [0 .. 11]))+    aad = B.pack (take 77 [100 ..])+    msg = B.pack (take 300 [1 ..])+    -- block-aligned chunks with a partial one last, below and above the+    -- eight blocks the C processes in a group+    splits = [([16], [16]), ([16, 32], [16, 16, 16]), ([64], [160, 32]), ([], [256])]+    chunks [] bs = [bs]+    chunks (n : ns) bs = let (h, t) = B.splitAt n bs in h : chunks ns t+    run step as ms =+        let a0 = foldl' aeadAppendHeader start as+            go a [] = ([], a)+            go a (m : rest) =+                let (c, a') = step a m+                    (cs, a'') = go a' rest+                 in (c : cs, a'')+            (outs, a1) = go a0 ms+         in (B.concat outs, BA.convert (aeadFinalize a1 16) :: ByteString)+    enc = run aeadEncrypt+    dec = run aeadDecrypt ([] :: [ByteString])+ spec :: Spec spec = do     testBlockCipher128 kats128 (undefined :: AES.AES128)@@ -454,5 +491,6 @@     aeadTagLengthTests     ccmMisuseTests     ocbIVLengthTests+    ocbChunkTests     gcmLongTests     oneShotTests
tests/BlockCipher/CAST5Spec.hs view
@@ -3,8 +3,13 @@ module BlockCipher.CAST5Spec (spec) where  import BlockCipher+import Imports++import Control.Exception (evaluate) import qualified Crypto.Cipher.CAST5 as CAST5-import Test.Hspec (Spec)+import Crypto.Cipher.Types+import Crypto.Error (throwCryptoError)+import qualified Data.ByteString as B  vectors_ecb =     -- key plaintext ciphertext@@ -25,4 +30,15 @@ kats = defaultKATs{kat_ECB = vectors_ecb}  spec :: Spec-spec = testBlockCipher kats (undefined :: CAST5.CAST5)+spec = do+    testBlockCipher kats (undefined :: CAST5.CAST5)+    describe "CAST5 ECB" $ do+        -- the short block used to come back as uninitialised memory+        it "refuses to encrypt a message that is not whole blocks" $+            evaluate (B.length (ecbEncrypt ctx (B.replicate 12 0)))+                `shouldThrow` anyErrorCall+        it "refuses to decrypt a message that is not whole blocks" $+            evaluate (B.length (ecbDecrypt ctx (B.replicate 12 0)))+                `shouldThrow` anyErrorCall+  where+    ctx = throwCryptoError (cipherInit (B.replicate 16 0x2b)) :: CAST5.CAST5
tests/ECDSASpec.hs view
@@ -1,8 +1,8 @@+{-# LANGUAGE ExistentialQuantification #-}+{-# LANGUAGE FlexibleContexts #-} -- The binary curves are deprecated and still supported, so the tests -- that hold them to their behaviour name them on purpose. {-# OPTIONS_GHC -Wno-deprecations #-}-{-# LANGUAGE ExistentialQuantification #-}-{-# LANGUAGE FlexibleContexts #-}  module ECDSASpec (spec) where @@ -136,6 +136,20 @@                     g256                     (ECDSA.pointNegate (Just ECDSA.Curve_P256R1) g256)     describe "recovery" $ do+        -- SEC 1 4.1.6 refuses these; they used to recover some key+        it "refuses s = 0, and an x at or past p" $ do+            let k1 = ECC.getCurveByName ECC.SEC_p256k1+                cc = ECC.common_curve k1+                n = ECC.ecc_n cc+                p = case k1 of+                    ECC.CurveFP (ECC.CurvePrime q _) -> q+                    _ -> error "secp256k1 is a prime curve"+                digest = hashWith SHA256 (B.pack [1, 2, 3])+                rec i r s =+                    ECC.recoverDigest k1 (ECC.ExtendedSignature i False (ECC.Signature r s)) digest+            rec 0 1 0 `shouldBe` Nothing+            rec 0 n 1 `shouldBe` Nothing+            rec 1 (p - n) 1 `shouldBe` Nothing         modifyMaxSuccess (const 100) $ testRecover ECC.SEC_p128r1         modifyMaxSuccess (const 100) $ testRecover ECC.SEC_p128r2         modifyMaxSuccess (const 100) $ testRecover ECC.SEC_p256k1
tests/EntropySpec.hs view
@@ -15,7 +15,12 @@ import Test.Hspec  import Crypto.Random.Entropy (EntropyError (..), getEntropy)-import Crypto.Random.Entropy.Unsafe (gatherBackend, replenish, supportedBackends)+import Crypto.Random.Entropy.Unsafe (+    gatherBackend,+    replenish,+    supportedBackends,+ )+import Crypto.Random.EntropyPool (createEntropyPoolWith, getEntropyFrom)  spec :: Spec spec = describe "the system entropy source" $ do@@ -50,6 +55,20 @@     it "says so with an exception when there is no source at all" $ do         r <- allocaBytes 16 $ \ptr -> try (replenish 16 [] ptr)         r `shouldBe` Left NoEntropySource++    -- an empty buffer was allocated for these and then written into+    it "refuses a negative length" $ do+        (getEntropy (-1) :: IO BS.ByteString) `shouldThrow` anyErrorCall+        (getEntropy (negate (2 ^ (32 :: Int)) + 64) :: IO BS.ByteString)+            `shouldThrow` anyErrorCall+        bs <- catMaybes `fmap` sequence supportedBackends+        pool <- createEntropyPoolWith 64 bs+        (getEntropyFrom pool (-1) :: IO BS.ByteString) `shouldThrow` anyErrorCall++    -- getEntropyFrom on a pool of size zero used to loop forever+    it "refuses an entropy pool of size zero" $ do+        bs <- catMaybes `fmap` sequence supportedBackends+        createEntropyPoolWith 0 bs `shouldThrow` anyErrorCall  lengthCase :: Int -> Spec lengthCase n =
tests/HashSpec.hs view
@@ -6,6 +6,7 @@     spec, ) where +import Control.Exception (evaluate) import Crypto.Hash  import Data.ByteArray (convert)@@ -591,6 +592,14 @@     -- the length goes into the configuration block, so it changes the chaining     -- value the message is hashed from: a longer digest is not an extension of     -- a shorter one, which is the opposite of how SHAKE behaves+    -- the C takes the bit length as uint32_t, which a larger one used to wrap+    it "refuses a size of 2^32 bits or more" $ do+        evaluate (hashWith (Skein512 :: Skein512 4294967296) v1)+            `shouldThrow` anyErrorCall+        evaluate (hashWith (SHAKE128 :: SHAKE128 4294967304) v1)+            `shouldThrow` anyErrorCall+        evaluate (hashWith (SHAKE256 :: SHAKE256 147573952589676412923) v1)+            `shouldThrow` anyErrorCall     it "answers a different size with an unrelated digest, not a longer one" $ do         let short = convert (hashWith (Skein512 :: Skein512 256) v1) :: ByteString             long = convert (hashWith (Skein512 :: Skein512 512) v1) :: ByteString@@ -600,15 +609,39 @@     h alg m = convert (hashWith alg m) :: ByteString     len alg = B.length (convert (hashWith alg v1) :: ByteString) +-- one update of 2^28 bytes or more used to overflow the bit count in C+largeUpdateTests :: Spec+largeUpdateTests = describe "one update of 256 MiB" $+    it "Whirlpool" $ do+        let chunk = B.replicate 65536 1+            whole = B.concat (replicate 4096 chunk)+        hashWith Whirlpool whole+            `shouldBe` hashFinalize (hashUpdates (hashInitWith Whirlpool) (replicate 4096 chunk))+ spec :: Spec spec = do     describe "KATs" $ mapM_ makeTestAlg expected     skeinNatTests+    largeUpdateTests     describe "KATs over several blocks" $         mapM_ (makeTestAlgWith longVectors) expectedLong     describe "Chunking" $ mapM_ makeTestChunk expected     describe "Prefix" $ mapM_ makeTestPrefix expectedPrefix     describe "Hybrid" $ mapM_ makeTestHybrid expectedPrefix+    describe "Prefix length outside [0, 2^32)" $ do+        -- it used to be cut to 32 bits, so 2^32 + 3 hashed three bytes+        let msg = B.pack [1 .. 100] :: ByteString+            full = hashWith SHA256 msg+        it "2^32 + 3 takes the whole input" $+            hashPrefixWith SHA256 msg (2 ^ (32 :: Int) + 3) `shouldBe` full+        it "2^32 takes the whole input" $+            hashPrefixWith SHA256 msg (2 ^ (32 :: Int)) `shouldBe` full+        it "-2^32 + 3 takes the whole input" $+            hashPrefixWith SHA256 msg (3 - 2 ^ (32 :: Int)) `shouldBe` full+        it "-1 takes the whole input" $+            hashPrefixWith SHA256 msg (-1) `shouldBe` full+        it "3 still takes three bytes" $+            hashPrefixWith SHA256 msg 3 `shouldBe` hashWith SHA256 (B.take 3 msg)     describe "Truncating" $ do         describe "SHAKE128" $             sequence_ $
tests/KDF/BCryptSpec.hs view
@@ -73,6 +73,10 @@         )     ] +-- | The 53 characters after the cost of a hash in 'expected'.+rest :: ByteString+rest = "$CCCCCCCCCCCCCCCCCCCCC.7uG0VCzI2bS7j6ymqJi9CdcdxiRTWNy"+ makeKATs = concatMap maketest (zip3 is passwords hashes)   where     is :: [Int]@@ -117,6 +121,12 @@             )                 `shouldBe` CryptoFailed CryptoError_ParameterInvalid     describe "cost" $ do+        -- "1:" was read as 1 * 10 + (':' - '0') = 20, a cost bcrypt accepts.+        it "refuses a cost that is not two digits" $+            [ validatePasswordEither ("" :: B.ByteString) (B.concat ["$2a$", c, rest])+            | c <- ["1:", "2/", "0?", ":0"]+            ]+                `shouldBe` replicate 4 (Left "Invalid bcrypt cost")         -- What made the old behaviour wrong was not the floor but that it was         -- silent: a request for cost 3 came back as a cost-10 hash and a         -- request for cost 50 as a cost-31 one, with nothing said either way.@@ -138,7 +148,9 @@             evaluate (bcrypt (3 :: Int) aSalt somePassword :: B.ByteString)                 `shouldThrow` (== CryptoError_ParameterInvalid)         it "takes the bottom of the range" $-            validatePassword somePassword (bcrypt (4 :: Int) aSalt somePassword :: B.ByteString)+            validatePassword+                somePassword+                (bcrypt (4 :: Int) aSalt somePassword :: B.ByteString)                 `shouldBe` True         it "writes the cost it was given, not another one" $             B.take 7 (bcrypt (4 :: Int) aSalt somePassword :: B.ByteString)
tests/KDF/PBKDF2Spec.hs view
@@ -113,6 +113,14 @@                 badPass                 badSalt                 `shouldBe` refused+        -- RFC 8018: at most 2^32 - 1 blocks; the fast path used to narrow+        -- the block count to 32 bits and leave the rest of the key unwritten+        it "rejects a key longer than 2^32 - 1 blocks" $ do+            let long h = PBKDF2.Parameters 1 ((2 ^ (32 :: Int) - 1) * h + 1)+            PBKDF2.tryGenerate badPrf (long 32) badPass badSalt `shouldBe` refused+            PBKDF2.tryFastPBKDF2_SHA1 (long 20) badPass badSalt `shouldBe` refused+            PBKDF2.tryFastPBKDF2_SHA256 (long 32) badPass badSalt `shouldBe` refused+            PBKDF2.tryFastPBKDF2_SHA512 (long 64) badPass badSalt `shouldBe` refused         it "reports them without raising" $ do             PBKDF2.tryGenerate badPrf (PBKDF2.Parameters 0 32) badPass badSalt                 `shouldBe` refused
tests/KDF/ScryptSpec.hs view
@@ -53,6 +53,9 @@             run' (Scrypt.Parameters 16 (-1) 1 32) `shouldBe` refused             run' (Scrypt.Parameters 16 8 0 32) `shouldBe` refused             run' (Scrypt.Parameters 16 8 (-1) 32) `shouldBe` refused+        -- the C indexes 32 * r words with int, which went negative+        it "rejects r of 2^26 or more" $+            run' (Scrypt.Parameters 2 (2 ^ (26 :: Int)) 1 32) `shouldBe` refused         it "rejects 128 * r * n that does not fit in an Int" $             run' (Scrypt.Parameters (2 ^ (57 :: Int)) 1 1 32) `shouldBe` refused   where
tests/MAC/Blake2Spec.hs view
@@ -1,10 +1,12 @@ {-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ScopedTypeVariables #-}  module MAC.Blake2Spec (spec) where -import Crypto.Hash (digestFromByteString)+import Control.Exception (evaluate)+import Crypto.Hash (digestFromByteString, hashBlockSize, hashWith) import Crypto.Hash.Algorithms import qualified Crypto.MAC.KeyedBlake2 as KB @@ -154,9 +156,13 @@ data MacIncremental a = MacIncremental ByteString ByteString (KB.KeyedBlake2 a)     deriving (Show, Eq) +-- | The longest key the algorithm takes: 64 bytes for b/bp, 32 for s/sp.+maxKey :: KB.HashBlake2 a => a -> Int+maxKey a = hashBlockSize a `div` 2+ instance KB.HashBlake2 a => Arbitrary (MacIncremental a) where     arbitrary = do-        key <- arbitraryBSof 32 64+        key <- arbitraryBSof 1 (maxKey (undefined :: a))         msg <- arbitraryBSof 1 99         return $ MacIncremental key msg (KB.keyedBlake2 key msg) @@ -166,7 +172,7 @@  instance KB.HashBlake2 a => Arbitrary (MacIncrementalList a) where     arbitrary = do-        key <- arbitraryBSof 32 64+        key <- arbitraryBSof 1 (maxKey (undefined :: a))         msgs <- choose (1, 20) >>= \n -> replicateM n (arbitraryBSof 1 99)         return $ MacIncrementalList key msgs (KB.keyedBlake2 key (B.concat msgs)) @@ -192,7 +198,49 @@     prop_inc1 _ (MacIncrementalList secret msgs result) =         result `assertEq` KB.finalize (foldl' KB.update (KB.initialize secret) msgs) +-- RFC 7693: a key of length zero means the unkeyed hash+emptyKeyTests :: Spec+emptyKeyTests = do+    it "Blake2b_512" $ check (Blake2b :: Blake2b 512)+    it "Blake2bp_512" $ check (Blake2bp :: Blake2bp 512)+    it "Blake2s_256" $ check (Blake2s :: Blake2s 256)+    it "Blake2sp_256" $ check (Blake2sp :: Blake2sp 256)+  where+    check :: KB.HashBlake2 a => a -> Expectation+    check a = forM_ ["", "abc", B.replicate 300 0x61] $ \m -> do+        KB.keyedBlake2GetDigest (KB.keyedBlake2 B.empty m) `shouldBe` hashWith a m+        KB.keyedBlake2GetDigest (KB.finalize (KB.update (KB.initialize B.empty) m))+            `shouldBe` hashWith a m++-- RFC 7693: the key may be longer than the digest; it used to be cut to the+-- digest size.  Expected values from Python's hashlib.+keyLengthTests :: Spec+keyLengthTests = do+    it "Blake2b_256 with a 64-byte key" $+        hex+            ( KB.keyedBlake2 (B.pack [0 .. 63]) ("abc" :: ByteString)+                :: KB.KeyedBlake2 (Blake2b 256)+            )+            `shouldBe` "dff38c978666dff5631db35ca15535520d134f5c8060ea569c6a178ad393719f"+    it "Blake2s_128 with a 32-byte key" $+        hex+            ( KB.keyedBlake2 (B.pack [0 .. 31]) ("abc" :: ByteString)+                :: KB.KeyedBlake2 (Blake2s 128)+            )+            `shouldBe` "61ba5f165c194692e09d12520cc4c74a"+    it "Blake2b_256 refuses a 65-byte key" $+        evaluate (KB.initialize (B.replicate 65 0) :: KB.Context (Blake2b 256))+            `shouldThrow` anyErrorCall+    it "Blake2s_256 refuses a 33-byte key" $+        evaluate (KB.initialize (B.replicate 33 0) :: KB.Context (Blake2s 256))+            `shouldThrow` anyErrorCall+  where+    hex :: KB.KeyedBlake2 a -> String+    hex (KB.KeyedBlake2 d) = show d+ spec :: Spec spec = do     describe "KATs" $ sequence_ macTests+    describe "key length" keyLengthTests+    describe "empty key" emptyKeyTests     describe "properties" $ sequence_ macIncrementalTests
tests/NumberSpec.hs view
@@ -293,6 +293,9 @@         let bits = m1bits + 1 -- make sure minimum is 2             r = withTestDRG testDRG $ generateParams bits (Just SetTwoHighest) False          in r >= 0 && numBits r == bits && testBit r (bits - 1) && testBit r (bits - 2)+    -- one bit has no second highest; this used to write a byte past the buffer+    prop "generate-param2 with one bit" $ \testDRG ->+        withTestDRG testDRG (generateParams 1 (Just SetTwoHighest) False) == 1     prop "generate-param-odd" $ \testDRG (Int1_2901 bits) ->         let r = withTestDRG testDRG $ generateParams bits Nothing True          in r >= 0 && odd r
tests/PubKey/DSASpec.hs view
@@ -427,6 +427,14 @@             DSA.signWith 4 priv SHA1 message `shouldSatisfy` isJust         it "verify with a non-invertible s returns False" $             DSA.verify SHA1 compositePub (DSA.Signature 1 3) message `shouldBe` False+        -- the parameters come with the key; p = 0 used to divide by zero+        it "verify with p = 0 returns False" $+            DSA.verify+                SHA256+                (DSA.PublicKey (DSA.Params 0 2 7) 3)+                (DSA.Signature 1 1)+                message+                `shouldBe` False   where     message = "message" :: ByteString     q = 11
tests/PubKey/ElGamalSpec.hs view
@@ -67,6 +67,14 @@     it "refuses a first component at or above the modulus" $         ElGamal.decrypt params priv (p, 1)             `shouldBe` CryptoFailed CryptoError_ParameterInvalid+    it "refuses a first component generating a tiny subgroup" $+        -- (p-1)^a is 1 or -1 as a is even or odd, so it told a's parity+        mapM_+            ( \c1 ->+                ElGamal.decrypt params priv (c1, 2)+                    `shouldBe` CryptoFailed CryptoError_ParameterInvalid+            )+            [1, p - 1]     it "refuses a second component out of range" $         ElGamal.decrypt params priv (2, p)             `shouldBe` CryptoFailed CryptoError_ParameterInvalid
tests/PubKey/P256Spec.hs view
@@ -10,7 +10,10 @@ import Crypto.Error import Crypto.Number.ModArithmetic (inverseCoprimes) import Crypto.Number.Serialize (i2ospOf, os2ip)+import Crypto.Random (DRG (..), withDRG) import Data.ByteArray (Bytes)+import qualified Data.ByteArray as BA+import qualified Data.ByteString as B  import Imports @@ -105,8 +108,25 @@         )     ] +-- hands out the given blocks in turn, so that a test can choose them+newtype Blocks = Blocks [B.ByteString]++instance DRG Blocks where+    randomBytesGenerate n (Blocks (b : bs)) = (BA.convert (B.take n b), Blocks bs)+    randomBytesGenerate _ (Blocks []) = error "Blocks: out of blocks"+ spec :: Spec spec = do+    -- n and above used to be reduced modulo n, favouring small scalars+    it "scalarGenerate draws again for 0 and for n and above" $+        let blocks =+                [ B.replicate 32 0xff+                , B.replicate 32 0+                , BA.convert (i2ospScalar curveN)+                , BA.convert (i2ospScalar 7)+                ]+         in p256ScalarToInteger (fst (withDRG (Blocks blocks) P256.scalarGenerate))+                `shouldBe` 7     describe "scalar" $ do         prop "marshalling" $ \(QAInteger r) ->             let rBytes = i2ospScalar r
tests/PubKey/PSSSpec.hs view
@@ -5,10 +5,10 @@ import Crypto.Number.Basic (numBits) import Crypto.Number.Serialize (i2ospOf_, os2ip) import Crypto.PubKey.RSA-import Crypto.PubKey.RSA.Prim (dp, ep) import qualified Crypto.PubKey.RSA.PSS as PSS-import qualified Data.ByteString as B+import Crypto.PubKey.RSA.Prim (dp, ep) import qualified Data.Bits as Bits+import qualified Data.ByteString as B import Data.Word (Word8)  import Imports@@ -484,6 +484,14 @@             verify' (i2ospOf_ k (os2ip s + modulus)) `shouldBe` False         it "a signature representative equal to the modulus is refused" $             verify' (i2ospOf_ k modulus) `shouldBe` False+        -- n = 1 gives an empty encoding, whose last byte used to be read+        it "a key too small for the encoding is refused, not raised on" $+            PSS.verify+                PSS.defaultPSSParamsSHA1+                (PublicKey 1 1 65537)+                ("message" :: ByteString)+                "\0"+                `shouldBe` False   where     key = rsaKey1     k = public_size (private_pub key)@@ -534,16 +542,17 @@      -- the first vector whose encoding, with a forbidden bit set, is still     -- below the modulus, paired as (honest, altered)-    altered key vs = firstVector-        [ ((v, signature v), (v, dp Nothing key em'))-        | v <- vs-        , let pub = private_pub key-              em = ep pub (signature v)-              bit = lowestSet (forbidden (numBits (public_n pub)))-              em' = B.cons (B.head em Bits..|. bit) (B.tail em)-        , B.head em Bits..&. forbidden (numBits (public_n pub)) == 0-        , os2ip em' < public_n pub-        ]+    altered key vs =+        firstVector+            [ ((v, signature v), (v, dp Nothing key em'))+            | v <- vs+            , let pub = private_pub key+                  em = ep pub (signature v)+                  bit = lowestSet (forbidden (numBits (public_n pub)))+                  em' = B.cons (B.head em Bits..|. bit) (B.tail em)+            , B.head em Bits..&. forbidden (numBits (public_n pub)) == 0+            , os2ip em' < public_n pub+            ]      -- the forbidden bit worth setting is the lowest of them: it is the one     -- that adds least, and an encoding at or past the modulus proves nothing
tests/PubKey/RSASpec.hs view
@@ -1,14 +1,15 @@+{-# LANGUAGE ExistentialQuantification #-}+{-# LANGUAGE OverloadedStrings #-} -- The properties below hold the new entry points against sign, signSafer -- and verify, which are deprecated as of this release.  Comparing against -- them is the point, so the warning is off here and nowhere else. {-# OPTIONS_GHC -Wno-deprecations #-}-{-# LANGUAGE ExistentialQuantification #-}-{-# LANGUAGE OverloadedStrings #-}  module PubKey.RSASpec (spec) where  import Control.Concurrent (forkIO) import Control.Concurrent.MVar+import Control.Exception (evaluate) import Crypto.Hash import Crypto.Number.ModArithmetic (inverse) import Crypto.Number.Serialize (i2osp, i2ospOf_, os2ip)@@ -19,8 +20,8 @@ import qualified Crypto.PubKey.RSA.PSS as PSS import Crypto.PubKey.RSA.Prim (ep) import qualified Crypto.PubKey.RSA.Prim as Prim-import qualified Data.ByteString as B import Data.Bits ((.|.))+import qualified Data.ByteString as B import Data.Either  import Imports@@ -141,7 +142,8 @@ -- and @s + n@ verify just as well as @s@ itself. doMalleabilityTest :: Show a => a -> VectorRSA -> Spec doMalleabilityTest i vector =-    describe (show i) $ mapM_ checks [("verify", verify'), ("verifyDigest", verifyDigest')]+    describe (show i) $+        mapM_ checks [("verify", verify'), ("verifyDigest", verifyDigest')]   where     -- Both routes, and absolutely rather than against each other: they     -- share the checks of RFC 8017, so a test that only made them agree@@ -282,7 +284,8 @@ crtFaultTests = describe "a fault in one CRT half" $     forM_ faults $ \(name, bad) -> describe name $ do         it "signs what the sound key signs" $-            RSA.sign Nothing (Just SHA256) bad m `shouldBe` RSA.sign Nothing (Just SHA256) key m+            RSA.sign Nothing (Just SHA256) bad m+                `shouldBe` RSA.sign Nothing (Just SHA256) key m         prop "signs with a blinder what the sound key signs" $ \testDRG ->             let blinder = withTestDRG testDRG $ RSA.generateBlinder (RSA.public_n pub)              in RSA.sign (Just blinder) (Just SHA256) bad m@@ -315,9 +318,14 @@ -- prime modulo the other, which is the part worked out without the extended -- Euclidean algorithm. keyGenerationTests :: Spec-keyGenerationTests =+keyGenerationTests = do     describe "generateWith" $         zipWithM_ check [katZero ..] vectorsSHA1+    -- no such e has an inverse modulo the even phi; generate used to loop+    it "generate refuses an e below 3 or even" $+        forM_ [-1, 0, 1, 2, 65536] $ \ex ->+            evaluate (RSA.generate 64 ex :: IO (RSA.PublicKey, RSA.PrivateKey))+                `shouldThrow` anyErrorCall   where     check i vector =         it (show i) $@@ -372,7 +380,6 @@         ]     exponents = [3, 5, 17, 257, 65537, 9, 15, 2] - -- | Every algorithm with a 'RSA.HashAlgorithmASN1' instance, so that a -- property quantifies over the lot of them rather than over the two or -- three somebody thought of.  Adding an instance and forgetting to add it@@ -418,7 +425,8 @@  -- | The digest a message has under an algorithm picked at runtime, which is -- what the existential leaves us able to say.-hashOf :: RSA.HashAlgorithmASN1 hashAlg => hashAlg -> ByteString -> Digest hashAlg+hashOf+    :: RSA.HashAlgorithmASN1 hashAlg => hashAlg -> ByteString -> Digest hashAlg hashOf = hashWith  -- | The operations that take a 'Digest' or a DigestInfo, against the ones@@ -553,7 +561,7 @@             return bk'      it "works for a key without its CRT values" $ do-        let bare = key {RSA.private_p = 0, RSA.private_q = 0}+        let bare = key{RSA.private_p = 0, RSA.private_q = 0}             go _ 41 = return ()             go bk i = do                 let dg = hashWith SHA256 (B.replicate i 0x62)@@ -570,7 +578,10 @@                     (s, bk') <- RSA.signDigestBlinded bk (hashWith SHA256 (B.replicate i 0x64))                     go bk' (i + 1) (s : acc)             sigs = withTestDRG testDRG (go (RSA.blindedKey key) 1 [])-         in sigs === [RSA.signDigest Nothing key (hashWith SHA256 (B.replicate i 0x64)) | i <- [1 .. 40]]+         in sigs+                === [ RSA.signDigest Nothing key (hashWith SHA256 (B.replicate i 0x64))+                    | i <- [1 .. 40]+                    ]      it "gives every thread a right answer through the Safer functions" $ do         dones <- forM [1 .. 8 :: Int] $ \t -> do@@ -588,7 +599,11 @@     -- More keys than the Safer functions remember, interleaved, so that the     -- table both hits and evicts.     it "keeps the Safer functions right across more keys than it remembers" $ do-        let keys = key : [snd (withTestDRG (TestDRG (s', 2, 3, 4, 5)) (RSA.generate 64 65537)) | s' <- [1 .. 5]]+        let keys =+                key+                    : [ snd (withTestDRG (TestDRG (s', 2, 3, 4, 5)) (RSA.generate 64 65537))+                      | s' <- [1 .. 5]+                      ]         forM_ [1 .. 12 :: Int] $ \i ->             forM_ keys $ \k -> do                 let dg = hashWith SHA256 (B.replicate i 0x63)
tests/PubKey/SecrecySpec.hs view
@@ -9,6 +9,7 @@ import Data.List (isInfixOf)  import Crypto.Debug (DebugShow, debugShow)+import qualified Crypto.ECC as ECC' import Crypto.Error (CryptoFailable, throwCryptoError) import qualified Crypto.PubKey.Curve448 as X448 import qualified Crypto.PubKey.Curve25519 as X25519@@ -24,6 +25,7 @@ import qualified Crypto.PubKey.Rabin.RW as RW  import qualified Data.ByteString as BS+import Data.Proxy (Proxy (..)) import Data.Word (Word8)  import Imports@@ -56,6 +58,15 @@ dsaParams :: DSA.Params dsaParams = DSA.Params{DSA.params_p = 0xabc2, DSA.params_g = 2, DSA.params_q = 0xabc3} +-- | P-384 and P-521 keep their scalar in an 'Integer'.+p384Scalar :: ECC'.Scalar ECC'.Curve_P384R1+p384Scalar =+    throwCryptoError $ ECC'.scalarFromInteger (Proxy :: Proxy ECC'.Curve_P384R1) d1++p521Scalar :: ECC'.Scalar ECC'.Curve_P521R1+p521Scalar =+    throwCryptoError $ ECC'.scalarFromInteger (Proxy :: Proxy ECC'.Curve_P521R1) d1+ ecdsaCurve :: ECC.Curve ecdsaCurve = ECC.getCurveByName ECC.SEC_p256r1 @@ -65,11 +76,14 @@ cases =     [ ("RSA.PrivateKey", show rsaPriv, [d1, d2, d3, d4, d5, d6])     , ("RSA.KeyPair", show (RSA.KeyPair rsaPriv), [d1, d2, d3, d4, d5, d6])+    , ("RSA.Blinder", show (RSA.Blinder d1 d2), [d1, d2])     , ("DSA.PrivateKey", show (DSA.PrivateKey dsaParams d1), [d1])     , ("DSA.KeyPair", show (DSA.KeyPair dsaParams 0xabc4 d1), [d1])     , ("ECDSA.PrivateKey", show (ECDSA.PrivateKey ecdsaCurve d1), [d1])     , ("ECDSA.KeyPair", show (ECDSA.KeyPair ecdsaCurve ECC.PointO d1), [d1])     , ("DH.PrivateNumber", show (DH.PrivateNumber d1), [d1])+    , ("Scalar Curve_P384R1", show (Just p384Scalar), [d1])+    , ("Scalar Curve_P521R1", show (Just p521Scalar), [d1])     ,         ( "Rabin.Basic.PrivateKey"         , show (Basic.PrivateKey (Basic.PublicKey 32 0xabc5) d1 d2 d3 d4)@@ -100,6 +114,8 @@     , ("ECDSA.PrivateKey", Reveal (ECDSA.PrivateKey ecdsaCurve d1), [d1])     , ("ECDSA.KeyPair", Reveal (ECDSA.KeyPair ecdsaCurve ECC.PointO d1), [d1])     , ("DH.PrivateNumber", Reveal (DH.PrivateNumber d1), [d1])+    , ("Scalar Curve_P384R1", Reveal p384Scalar, [d1])+    , ("Scalar Curve_P521R1", Reveal p521Scalar, [d1])     ,         ( "Rabin.Basic.PrivateKey"         , Reveal (Basic.PrivateKey (Basic.PublicKey 32 0xabc5) d1 d2 d3 d4)
tests/StreamCipher/ChaChaPoly1305Spec.hs view
@@ -9,9 +9,12 @@ import Imports import MAC.Poly1305Spec () +import Control.Exception (evaluate) import Data.Bits (xor) import qualified Data.ByteArray as B (convert) import qualified Data.ByteString as B+import Data.ByteString.Unsafe (unsafePackCStringLen)+import Foreign.Ptr (nullPtr)  plaintext     , aad@@ -131,7 +134,28 @@     it "nonce increment" runNonceInc     it "RFC8439 A5 enc" rfc8439encrypt     it "RFC8439 A5 dec" rfc8439decrypt+    -- each piece used to be padded to 16 bytes as if it were the whole header+    it "RFC8439 A5 with the header in pieces" $ do+        let a0 = throwCryptoError (CP.aeadChacha20poly1305Init a5key a5nonce)+            pieces = [B.take 5 a5aad, B.empty, B.drop 5 a5aad]+            headed = foldl' aeadAppendHeader a0 pieces+            (ct, a1) = aeadEncrypt headed a5plain+            (pt, a2) = aeadDecrypt headed a5cipher+        ct `shouldBe` a5cipher+        B.convert (aeadFinalize a1 16) `shouldBe` a5tag+        pt `shouldBe` a5plain+        B.convert (aeadFinalize a2 16) `shouldBe` a5tag     oneShotTests+    -- the 32-bit counter of a 96-bit nonce used to carry into the nonce;+    -- the input is only a length, which the check refuses before reading+    it "refuses a message past 2^38 - 64 bytes with a 96-bit nonce" $ do+        huge <- unsafePackCStringLen (nullPtr, 2 ^ (38 :: Int) - 63)+        let st =+                CP.initialize+                    (throwCryptoError $ CP.key (B.replicate 32 0))+                    (throwCryptoError $ CP.nonce12 (B.replicate 12 0))+        evaluate (fst (CP.encrypt huge st)) `shouldThrow` anyErrorCall+        evaluate (fst (CP.decrypt huge st)) `shouldThrow` anyErrorCall   where     runEncrypt =         let ini =@@ -195,6 +219,9 @@                 [ eqTest "nonce12a" nonce2 $ B.convert . CP.incrementNonce $ n1                 , eqTest "nonce12b" nonce4 $ B.convert . CP.incrementNonce $ n3                 , eqTest "nonce12c" nonce1 $ B.convert . CP.incrementNonce $ n5+                , eqTest "nonce12d" (B.snoc (B.replicate 11 0) 1) $+                    B.convert . CP.incrementNonce $+                        throwCryptoError (CP.nonce12 $ B.snoc (B.replicate 11 0xff) 0)                 , eqTest "nonce8a" (B.concat [constant, nonce7]) $                     B.convert . CP.incrementNonce $                         n6@@ -250,8 +277,10 @@     it "agrees with the step-at-a-time interface over a different message" $         let msg = "another message, of a length that is not a multiple of 16" :: B.ByteString             ad = "\x01\x02\x03" :: B.ByteString-            ini = CP.initialize (throwCryptoError $ CP.key key)-                                (throwCryptoError $ CP.nonce12 nonce12)+            ini =+                CP.initialize+                    (throwCryptoError $ CP.key key)+                    (throwCryptoError $ CP.nonce12 nonce12)             afterAAD = CP.finalizeAAD (CP.appendAAD ad ini)             (out, afterEnc) = CP.encrypt msg afterAAD             t = CP.finalize afterEnc
tests/StreamCipher/RC4Spec.hs view
@@ -3,6 +3,8 @@  module StreamCipher.RC4Spec where +import Control.Exception (evaluate)+import qualified Data.ByteString as B import Test.Hspec  import qualified Crypto.Cipher.RC4 as RC4@@ -30,10 +32,17 @@     ]  spec :: Spec-spec =-    sequence_ $-        zipWith toKatTest is vectors+spec = do+    sequence_ $ zipWith toKatTest is vectors+    -- the C reduced the key index modulo the key length, so dividing by zero+    it "refuses an empty key" $+        evaluate (RC4.initialize B.empty) `shouldThrow` anyErrorCall+    -- only the first 256 bytes are used+    it "ignores key bytes past 256" $+        snd (RC4.generate (RC4.initialize (long 0)) 64)+            `shouldBe` (snd (RC4.generate (RC4.initialize (long 1)) 64) :: ByteString)   where+    long b = B.replicate 256 7 `B.append` B.replicate 100 b     toKatTest i (key, plainText, cipherText) =         it             (show i)
tests/StreamCipher/SalsaSpec.hs view
@@ -2,6 +2,7 @@  module StreamCipher.SalsaSpec (spec) where +import Control.Exception (evaluate) import qualified Crypto.Cipher.Salsa as Salsa import qualified Data.ByteString as B @@ -74,7 +75,15 @@     prop "generate-combine" salsaGenerateCombine     prop "chunking-generate" salsaGenerateChunks     prop "chunking-combine" salsaCombineChunks+    -- its last word used to start the block counter, so nonces one apart+    -- shared all but one block of keystream+    it "refuses a 96-bit nonce" $+        evaluate+            (fst (Salsa.generate (Salsa.initialize 20 key32 nonce12) 64) :: ByteString)+            `shouldThrow` anyErrorCall   where+    key32 = B.replicate 32 0+    nonce12 = B.replicate 12 0     salsaRunSimple expected rounds key nonce =         let salsa = Salsa.initialize rounds key nonce          in salsaLoop 0 salsa expected `shouldBe` map snd expected