{-# LANGUAGE PackageImports #-}
{-# LANGUAGE Strict         #-}

module Foreign.Erlang.Digest
    ( genChallenge
    , genDigest
    ) where

import           "cryptonite" Crypto.Hash           (MD5 (MD5), hashFinalize,
                                                     hashInitWith, hashUpdate)
import           Data.ByteArray        (convert)
import qualified Data.ByteString       as BS
import qualified Data.ByteString.Char8 as CS
import           Data.Word
import           System.Random         (randomIO)

genChallenge :: IO Word32
genChallenge :: IO Word32
genChallenge = IO Word32
forall a. Random a => IO a
randomIO

genDigest :: Word32 -> BS.ByteString -> BS.ByteString
genDigest :: Word32 -> ByteString -> ByteString
genDigest Word32
challenge ByteString
cookie =
    let ctx0 :: Context MD5
ctx0 = MD5 -> Context MD5
forall alg. HashAlgorithm alg => alg -> Context alg
hashInitWith MD5
MD5
        ctx1 :: Context MD5
ctx1 = Context MD5 -> ByteString -> Context MD5
forall ba a.
(ByteArrayAccess ba, HashAlgorithm a) =>
Context a -> ba -> Context a
hashUpdate Context MD5
ctx0 ByteString
cookie
        ctx2 :: Context MD5
ctx2 = Context MD5 -> ByteString -> Context MD5
forall ba a.
(ByteArrayAccess ba, HashAlgorithm a) =>
Context a -> ba -> Context a
hashUpdate Context MD5
ctx1 (String -> ByteString
CS.pack (Word32 -> String
forall a. Show a => a -> String
show Word32
challenge))
        digest :: Digest MD5
digest = Context MD5 -> Digest MD5
forall a. HashAlgorithm a => Context a -> Digest a
hashFinalize Context MD5
ctx2
    in
        Digest MD5 -> ByteString
forall bin bout.
(ByteArrayAccess bin, ByteArray bout) =>
bin -> bout
convert Digest MD5
digest