module Cometa.Crypto.Pbkdf2 (deriveBytes) where
import Cometa.Error (Error (..))
import qualified Cometa.Internal.Pbkdf2Pure as Internal
import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString
deriveBytes :: ByteString -> ByteString -> Integer -> Integer -> Either Error ByteString
deriveBytes :: ByteString
-> ByteString -> Integer -> Integer -> Either Error ByteString
deriveBytes ByteString
password ByteString
salt Integer
iterations Integer
size
| ByteString -> Bool
ByteString.null ByteString
salt = Error -> Either Error ByteString
forall a b. a -> Either a b
Left Error
EmptyPbkdf2Salt
| Integer
iterations Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Integer
1 Bool -> Bool -> Bool
|| Integer
iterations Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Integer
4294967295 = Error -> Either Error ByteString
forall a b. a -> Either a b
Left (Integer -> Error
InvalidPbkdf2Iterations Integer
iterations)
| Integer
size Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Integer
1 Bool -> Bool -> Bool
|| Integer
size Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Integer -> Integer -> Integer
forall a. Ord a => a -> a -> a
min (Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Int
forall a. Bounded a => a
maxBound :: Int)) (Integer
64 Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* (Integer
2 Integer -> Int -> Integer
forall a b. (Num a, Integral b) => a -> b -> a
^ (Int
32 :: Int) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
- Integer
1)) = Error -> Either Error ByteString
forall a b. a -> Either a b
Left (Integer -> Error
InvalidPbkdf2OutputLength Integer
size)
| Bool
otherwise = ByteString
-> ByteString -> Word32 -> Int -> Either Error ByteString
Internal.deriveBytes ByteString
password ByteString
salt (Integer -> Word32
forall a. Num a => Integer -> a
fromInteger Integer
iterations) (Integer -> Int
forall a. Num a => Integer -> a
fromInteger Integer
size)