module Network.Hawk.Algo
( HawkAlgo(..)
, HawkAlgoCls(..)
, Key(..)
, SHA1(SHA1)
, SHA256(SHA256)
, readHawkAlgo
) where
import Crypto.Hash (Digest (..), hash)
import Crypto.Hash.Algorithms (SHA1 (..), SHA256 (..))
import Crypto.MAC.HMAC (HMAC, hmac, hmacGetDigest)
import Data.ByteArray (ByteArrayAccess)
import qualified Data.ByteArray.Encoding as B (Base (..), convertToBase)
import Data.ByteString (ByteString)
import Data.Char (toLower)
import Data.String (IsString)
import GHC.Generics
import Network.Iron.Util (b64)
newtype Key = Key ByteString deriving (Show, Eq, Generic, ByteArrayAccess, IsString)
class HawkAlgoCls a where
hawkHash :: a -> ByteString -> ByteString
hawkMac :: a -> Key -> ByteString -> ByteString
data HawkAlgo = forall alg . (HawkAlgoCls alg, Show alg) => HawkAlgo alg
instance HawkAlgoCls HawkAlgo where
hawkHash (HawkAlgo alg) = hawkHash alg
hawkMac (HawkAlgo alg) = hawkMac alg
instance Show HawkAlgo where
show (HawkAlgo a) = map toLower (show a)
instance HawkAlgoCls SHA1 where
hawkHash _ bs = b64 (hash bs :: Digest SHA1)
hawkMac _ k bs = b64 $ hmacGetDigest (hmac k bs :: HMAC SHA1)
instance HawkAlgoCls SHA256 where
hawkHash _ bs = b64 (hash bs :: Digest SHA256)
hawkMac _ k bs = b64 $ hmacGetDigest (hmac k bs :: HMAC SHA256)
instance Eq HawkAlgo where
_ == _ = True
readHawkAlgo :: String -> Maybe HawkAlgo
readHawkAlgo a = case map toLower a of
"sha1" -> Just (HawkAlgo SHA1)
"sha256" -> Just (HawkAlgo SHA256)
_ -> Nothing