module Crypto.Saltine.Core.Auth (
Key, Authenticator,
newKey,
auth, verify
) where
import Crypto.Saltine.Internal.Auth
( c_auth
, c_auth_verify
, Key(..)
, Authenticator(..)
)
import Crypto.Saltine.Internal.Util as U
import Data.ByteString (ByteString)
import qualified Crypto.Saltine.Internal.Auth as Bytes
newKey :: IO Key
newKey :: IO Key
newKey = ByteString -> Key
Key (ByteString -> Key) -> IO ByteString -> IO Key
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Int -> IO ByteString
randomByteString Int
Bytes.auth_keybytes
auth :: Key
-> ByteString
-> Authenticator
auth :: Key -> ByteString -> Authenticator
auth (Key ByteString
key) ByteString
msg =
ByteString -> Authenticator
Au (ByteString -> Authenticator)
-> ((Ptr CChar -> IO CInt) -> ByteString)
-> (Ptr CChar -> IO CInt)
-> Authenticator
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (CInt, ByteString) -> ByteString
forall a b. (a, b) -> b
snd ((CInt, ByteString) -> ByteString)
-> ((Ptr CChar -> IO CInt) -> (CInt, ByteString))
-> (Ptr CChar -> IO CInt)
-> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> (Ptr CChar -> IO CInt) -> (CInt, ByteString)
forall b. Int -> (Ptr CChar -> IO b) -> (b, ByteString)
buildUnsafeByteString Int
Bytes.auth_bytes ((Ptr CChar -> IO CInt) -> Authenticator)
-> (Ptr CChar -> IO CInt) -> Authenticator
forall a b. (a -> b) -> a -> b
$ \Ptr CChar
pa ->
[ByteString] -> ([CStringLen] -> IO CInt) -> IO CInt
forall b. [ByteString] -> ([CStringLen] -> IO b) -> IO b
constByteStrings [ByteString
key, ByteString
msg] (([CStringLen] -> IO CInt) -> IO CInt)
-> ([CStringLen] -> IO CInt) -> IO CInt
forall a b. (a -> b) -> a -> b
$ \[(Ptr CChar
pk, Int
_), (Ptr CChar
pm, Int
mlen)] ->
Ptr CChar -> Ptr CChar -> CULLong -> Ptr CChar -> IO CInt
c_auth Ptr CChar
pa Ptr CChar
pm (Int -> CULLong
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
mlen) Ptr CChar
pk
verify :: Key
-> Authenticator
-> ByteString
-> Bool
verify :: Key -> Authenticator -> ByteString -> Bool
verify (Key ByteString
key) (Au ByteString
a) ByteString
msg =
IO CInt -> Bool
unsafeDidSucceed (IO CInt -> Bool) -> IO CInt -> Bool
forall a b. (a -> b) -> a -> b
$ [ByteString] -> ([CStringLen] -> IO CInt) -> IO CInt
forall b. [ByteString] -> ([CStringLen] -> IO b) -> IO b
constByteStrings [ByteString
key, ByteString
msg, ByteString
a] (([CStringLen] -> IO CInt) -> IO CInt)
-> ([CStringLen] -> IO CInt) -> IO CInt
forall a b. (a -> b) -> a -> b
$ \[(Ptr CChar
pk, Int
_), (Ptr CChar
pm, Int
mlen), (Ptr CChar
pa, Int
_)] ->
CInt -> IO CInt
forall (m :: * -> *) a. Monad m => a -> m a
return (CInt -> IO CInt) -> CInt -> IO CInt
forall a b. (a -> b) -> a -> b
$ Ptr CChar -> Ptr CChar -> CULLong -> Ptr CChar -> CInt
c_auth_verify Ptr CChar
pa Ptr CChar
pm (Int -> CULLong
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
mlen) Ptr CChar
pk