{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}
-- | 256 and 512 bit variants of the Threefish block cipher used as the
--   foundation of the Skein hash function.
module Crypto.Threefish (  
    Block256, Threefish256, Key256,
    Block512, Threefish512, Key512,
    Tweak (..), parseHex, readHex, defaultTweak,
    Threefish (..)
) where
import Crypto.Threefish.Threefish256 as TF256
import Crypto.Threefish.Threefish512 as TF512
import Crypto.Threefish.Common as Common
import Data.Serialize
import qualified Data.ByteString as BS

class Serialize a => Threefish a b | a -> b where
  -- | Create a Threefish key using a custom tweak value.
  threefishKey :: Tweak -> a -> b
  -- | Encrypt a block using the given key and tweak value.
  threefishEncrypt :: a -> Tweak -> a -> a
  -- | Decrypt a block using the given key and tweak value.
  threefishDecrypt :: a -> Tweak -> a -> a
  -- | Create an appropriately sized block.
  toBlock :: BS.ByteString -> Maybe a
  -- | Extract the contents of a block.
  fromBlock :: a -> BS.ByteString

instance Threefish Block256 Threefish256 where
  threefishKey :: Tweak -> Block256 -> Threefish256
threefishKey = Tweak -> Block256 -> Threefish256
Threefish256
  threefishEncrypt :: Block256 -> Tweak -> Block256 -> Block256
threefishEncrypt = Block256 -> Tweak -> Block256 -> Block256
encrypt256
  threefishDecrypt :: Block256 -> Tweak -> Block256 -> Block256
threefishDecrypt = Block256 -> Tweak -> Block256 -> Block256
decrypt256
  toBlock :: ByteString -> Maybe Block256
toBlock ByteString
bs = if ByteString -> Int
BS.length ByteString
bs Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
32 then Maybe Block256
forall a. Maybe a
Nothing else Block256 -> Maybe Block256
forall a. a -> Maybe a
Just (ByteString -> Block256
Block256 ByteString
bs)
  fromBlock :: Block256 -> ByteString
fromBlock (Block256 ByteString
bs) = ByteString
bs

instance Threefish Block512 Threefish512 where
  threefishKey :: Tweak -> Block512 -> Threefish512
threefishKey = Tweak -> Block512 -> Threefish512
Threefish512
  threefishEncrypt :: Block512 -> Tweak -> Block512 -> Block512
threefishEncrypt = Block512 -> Tweak -> Block512 -> Block512
encrypt512
  threefishDecrypt :: Block512 -> Tweak -> Block512 -> Block512
threefishDecrypt = Block512 -> Tweak -> Block512 -> Block512
decrypt512
  toBlock :: ByteString -> Maybe Block512
toBlock ByteString
bs =
    case ByteString -> Either String Block512
forall a. Serialize a => ByteString -> Either String a
decode ByteString
bs of
      Right Block512
block -> Block512 -> Maybe Block512
forall a. a -> Maybe a
Just Block512
block
      Either String Block512
_           -> Maybe Block512
forall a. Maybe a
Nothing
  fromBlock :: Block512 -> ByteString
fromBlock = Block512 -> ByteString
forall a. Serialize a => a -> ByteString
encode