module Crypto.Cipher.Utils
    ( validateKeySize
    ) where

import Crypto.Error
import Crypto.Cipher.Types

import Data.ByteArray as BA

validateKeySize :: (ByteArrayAccess key, Cipher cipher) => cipher -> key -> CryptoFailable key
validateKeySize :: forall key cipher.
(ByteArrayAccess key, Cipher cipher) =>
cipher -> key -> CryptoFailable key
validateKeySize cipher
c key
k = if Bool
validKeyLength
                      then forall a. a -> CryptoFailable a
CryptoPassed key
k
                      else forall a. CryptoError -> CryptoFailable a
CryptoFailed CryptoError
CryptoError_KeySizeInvalid
  where keyLength :: Int
keyLength = forall ba. ByteArrayAccess ba => ba -> Int
BA.length key
k
        validKeyLength :: Bool
validKeyLength = case forall cipher. Cipher cipher => cipher -> KeySizeSpecifier
cipherKeySize cipher
c of
          KeySizeRange Int
low Int
high -> Int
keyLength forall a. Ord a => a -> a -> Bool
>= Int
low Bool -> Bool -> Bool
&& Int
keyLength forall a. Ord a => a -> a -> Bool
<= Int
high
          KeySizeEnum [Int]
lengths -> Int
keyLength forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Int]
lengths
          KeySizeFixed Int
s -> Int
keyLength forall a. Eq a => a -> a -> Bool
== Int
s