module Data.ContentStore.Digest(DigestAlgorithm,
getDigestAlgorithm,
digestName,
digestSize,
digestInit,
DigestContext,
digestUpdate,
digestUpdates,
digestFinalize,
digestByteString,
digestLazyByteString,
ObjectDigest,
toHex,
fromByteString)
where
import Crypto.Hash
import Data.ByteArray(Bytes, ByteArrayAccess, convert)
import Data.ByteArray.Encoding(Base(..), convertToBase)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Text as T
import Data.Text.Encoding(decodeUtf8)
data DigestAlgorithm = forall a. (HashAlgorithm a, Show a) => DigestAlgorithm a
data DigestContext = forall a. HashAlgorithm a => DigestContext (Context a)
newtype ObjectDigest = ObjectDigest Bytes
deriving (Eq, Ord, ByteArrayAccess)
instance Show ObjectDigest where
show (ObjectDigest b) = show b
fromDigest :: HashAlgorithm a => Digest a -> ObjectDigest
fromDigest = ObjectDigest . convert
hashLazyWith :: HashAlgorithm a => a -> LBS.ByteString -> Digest a
hashLazyWith _ = hashlazy
digestName :: DigestAlgorithm -> String
digestName (DigestAlgorithm a) = show a
digestSize :: DigestAlgorithm -> Int
digestSize (DigestAlgorithm a) = hashDigestSize a
digestInit :: DigestAlgorithm -> DigestContext
digestInit (DigestAlgorithm a) = DigestContext $ hashInitWith a
digestUpdate :: ByteArrayAccess ba => DigestContext -> ba -> DigestContext
digestUpdate (DigestContext ctx) = DigestContext . hashUpdate ctx
digestUpdates :: ByteArrayAccess ba => DigestContext -> [ba] -> DigestContext
digestUpdates (DigestContext ctx) = DigestContext . hashUpdates ctx
digestFinalize :: DigestContext -> ObjectDigest
digestFinalize (DigestContext ctx) = fromDigest $ hashFinalize ctx
digestByteString :: DigestAlgorithm -> BS.ByteString -> ObjectDigest
digestByteString (DigestAlgorithm a) = fromDigest . hashWith a
digestLazyByteString :: DigestAlgorithm -> LBS.ByteString -> ObjectDigest
digestLazyByteString (DigestAlgorithm a) = fromDigest . hashLazyWith a
fromByteString :: ByteArrayAccess ba => DigestAlgorithm -> ba -> Maybe ObjectDigest
fromByteString (DigestAlgorithm a) = fmap fromDigest . digestFromByteStringWith a
digestFromByteStringWith :: (HashAlgorithm a, ByteArrayAccess ba) => a -> ba -> Maybe (Digest a)
digestFromByteStringWith _ = digestFromByteString
toHex :: ObjectDigest -> String
toHex = T.unpack . decodeUtf8 . convertToBase Base16
getDigestAlgorithm :: T.Text -> Maybe DigestAlgorithm
getDigestAlgorithm "SHA256" = Just $ DigestAlgorithm SHA256
getDigestAlgorithm "SHA512" = Just $ DigestAlgorithm SHA512
getDigestAlgorithm "BLAKE2" = Just $ DigestAlgorithm Blake2b_512
getDigestAlgorithm "BLAKE2b" = Just $ DigestAlgorithm Blake2b_512
getDigestAlgorithm "BLAKE2b512" = Just $ DigestAlgorithm Blake2b_512
getDigestAlgorithm "BLAKE2b256" = Just $ DigestAlgorithm Blake2b_256
getDigestAlgorithm "BLAKE2s" = Just $ DigestAlgorithm Blake2s_256
getDigestAlgorithm "BLAKE2s256" = Just $ DigestAlgorithm Blake2s_256
getDigestAlgorithm _ = Nothing