packages feed

web3-tools-0.1.0.0: src/Crypto/Hash/Keccak.hs

module Crypto.Hash.Keccak
  ( hashKeccak256,
    hashKeccak256Str,
  )
where

import qualified Crypto.Hash as H
import Data.ByteArray (convert)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BS8
import Data.Char (toLower)
import Text.Printf (printf)

-- | Hash data using Keccak256
hashKeccak256 :: ByteString -> H.Digest H.Keccak_256
hashKeccak256 = H.hash

hashKeccak256BS :: ByteString -> ByteString
hashKeccak256BS = convert . H.hashWith H.Keccak_256

-- | Hash a string using Keccak256 and return the result as a string
hashKeccak256Str :: String -> String
hashKeccak256Str = showBytes . hashKeccak256BS . BS8.pack . fmap toLower

-- | Convert a ByteString to a hexadecimal string
showBytes :: ByteString -> String
showBytes = concatMap (printf "%02x") . B.unpack