packages feed

spade-0.1.0.7: src/Interpreter/Lib/Crypto.hs

module Interpreter.Lib.Crypto where

import Crypto.Hash
import Data.ByteString as BS
import Data.ByteArray
import Data.Coerce
import Data.Text

import Interpreter.Common

builtInHash :: BuiltInFnWithDoc '[ '("algo", Text), '("bytes", BS.ByteString) ]
builtInHash ((coerce -> (algo :: Text)) :> (coerce -> (bs :: ByteString)) :> EmptyArgs) =
  case algo of
    "md5" -> pure $ Just $ BytesValue $ convert $ hash @_ @MD5 bs
    _ -> error "Unknown algorithm"

builtInHashInit :: BuiltInFnWithDoc '[ '("algo", Text) ]
builtInHashInit ((coerce -> (algo :: Text)) :> EmptyArgs) =
  case algo of
    "md5" -> pure $ Just $ HashContextValue (MD5HashContext (hashInit @MD5))
    _ -> error "Unknown algorithm"

builtInHashUpdate :: BuiltInFnWithDoc '[ '("context", HashContext), '("input", ByteString) ]
builtInHashUpdate ((coerce -> (context :: HashContext)) :> (coerce -> (input :: ByteString)) :> EmptyArgs) =
  case context of
    MD5HashContext ctx -> do
      pure $ Just $ HashContextValue (MD5HashContext $ hashUpdate ctx input)

builtInHashFinalize :: BuiltInFnWithDoc '[ '("context", HashContext) ]
builtInHashFinalize ((coerce -> (context :: HashContext)) :> EmptyArgs) =
  case context of
    MD5HashContext ctx -> do
      pure $ Just $ BytesValue $ convert $ (hashFinalize ctx)