{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module Cardano.Crypto.Hash.Short
( ShortHash
, MD5Prefix
)
where
import Cardano.Crypto.Hash.Class
import qualified "cryptonite" Crypto.Hash as H
import qualified Data.ByteArray as BA
import qualified Data.ByteString as B
import GHC.TypeLits (Nat, KnownNat, CmpNat, natVal)
import Data.Proxy (Proxy (..))
type ShortHash = MD5Prefix 8
data MD5Prefix (n :: Nat)
instance (KnownNat n, CmpNat n 33 ~ 'LT) => HashAlgorithm (MD5Prefix n) where
type SizeHash (MD5Prefix n) = n
hashAlgorithmName :: proxy (MD5Prefix n) -> String
hashAlgorithmName proxy (MD5Prefix n)
_ = String
"md5_prefix_" String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Integer -> String
forall a. Show a => a -> String
show (Proxy n -> Integer
forall (n :: Nat) (proxy :: Nat -> *).
KnownNat n =>
proxy n -> Integer
natVal (Proxy n
forall k (t :: k). Proxy t
Proxy :: Proxy n))
digest :: proxy (MD5Prefix n) -> ByteString -> ByteString
digest proxy (MD5Prefix n)
p =
Int -> ByteString -> ByteString
B.take (Word -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (proxy (MD5Prefix n) -> Word
forall h (proxy :: * -> *). HashAlgorithm h => proxy h -> Word
sizeHash proxy (MD5Prefix n)
p)) (ByteString -> ByteString)
-> (ByteString -> ByteString) -> ByteString -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
Digest MD5 -> ByteString
forall bin bout.
(ByteArrayAccess bin, ByteArray bout) =>
bin -> bout
BA.convert (Digest MD5 -> ByteString)
-> (ByteString -> Digest MD5) -> ByteString -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
(ByteArrayAccess ByteString, HashAlgorithm MD5) =>
ByteString -> Digest MD5
forall ba a.
(ByteArrayAccess ba, HashAlgorithm a) =>
ba -> Digest a
H.hash @ByteString @H.MD5