-- Hoogle documentation, generated by Haddock
-- See Hoogle, http://www.haskell.org/hoogle/


-- | The raaz cryptographic library.
--   
--   Raaz is a cryptographic library for Haskell. The library is designed
--   with a special emphasis on using the type system of Haskell to
--   eliminate a large set of vulnerabilities like buffer overflows, timing
--   attacks etc. It also strives to achieve this safety with no compromise
--   on performance.
@package raaz
@version 0.2.1


-- | This module gives functions that check at runtime whether the
--   underlying cpu supports given features. CPU features are architecture
--   specific. However, functions from this module are guaranteed to be
--   defined always -- they return <a>False</a> for incompatible
--   architecture. For example, the flag <a>avx2</a> is relevant only for a
--   an X86 architecture. So it is defined false, for say the ARM
--   architecture.
module Raaz.Core.CpuSupports

-- | Check whether the cpu supports sse extension.
sse :: Bool

-- | Check whether the cpu supports sse2 extension.
sse2 :: Bool

-- | Check whether the cpu supports sse3 extension.
sse3 :: Bool

-- | Check whether the cpu supports sse4_1 extension.
sse4_1 :: Bool

-- | Check whether the cpu supports sse-4.2 extension.
sse4_2 :: Bool

-- | Check whether the cpu supports avx extension.
avx :: Bool

-- | Check whether the cpu supports avx2 extension.
avx2 :: Bool


-- | A module that abstracts out monoidal actions.
module Raaz.Core.MonoidalAction

-- | A monoid <tt>m</tt> acting on the left of a space. Think of a left
--   action as a multiplication with the monoid. It should satisfy the law:
--   
--   <pre>
--   1 &lt;.&gt; p = p                         -- identity
--   a &lt;&gt; b &lt;.&gt; p  = a &lt;.&gt; b &lt;.&gt; p   -- successive displacements
--   </pre>
class Monoid m => LAction m space
(<.>) :: LAction m space => m -> space -> space
infixr 5 <.>

-- | A left-monoid action on a monoidal-space, i.e. the space on which the
--   monoid acts is itself a monoid, is <i>distributive</i> if it satisfies
--   the law:
--   
--   <pre>
--   a &lt;.&gt; p &lt;&gt; q  = (a &lt;.&gt; p) &lt;&gt; (a &lt;.&gt; q).
--   </pre>
--   
--   The above law implies that every element <tt>m</tt> is a monoid
--   homomorphism.
class (LAction m space, Monoid space) => Distributive m space

-- | The semidirect product Space ⋊ Monoid. For monoids acting on monoidal
--   spaces distributively the semi-direct product is itself a monoid. It
--   turns out that data serialisers can essentially seen as a semidirect
--   product.
data SemiR space m
SemiR :: space -> !m -> SemiR space m

-- | An alternate symbol for &lt;&gt; more useful in the additive context.
(<++>) :: Monoid m => m -> m -> m
infixr 5 <++>

-- | From the an element of semi-direct product Space ⋊ Monoid return the
--   point.
semiRSpace :: SemiR space m -> space

-- | From the an element of semi-direct product Space ⋊ Monoid return the
--   monoid element.
semiRMonoid :: SemiR space m -> m

-- | Uniform action of a monoid on a functor. The laws that should be
--   satisfied are:
--   
--   <pre>
--   1 &lt;&lt;.&gt;&gt; fx  = fx
--   (a &lt;&gt; b) &lt;&lt;.&gt;&gt; fx  = a . (b &lt;&lt;.&gt;&gt; fx)
--   m &lt;&lt;.&gt;&gt; fmap f u = fmap f (m &lt;&lt;.&gt;&gt; u)   -- acts uniformly
--   </pre>
class (Monoid m, Functor f) => LActionF m f
(<<.>>) :: LActionF m f => m -> f a -> f a
infixr 5 <<.>>

-- | The generalisation of distributivity to applicative functors. This
--   generalisation is what allows us to capture applicative functors like
--   parsers. For an applicative functor, and a monoid acting uniformly on
--   it, we say that the action is distributive if the following laws are
--   satisfied:
--   
--   <pre>
--   m &lt;&lt;.&gt;&gt; (pure a) = pure a            -- pure values are stoic
--   m &lt;&lt;.&gt;&gt; (a &lt;*&gt; b) = (m &lt;&lt;.&gt;&gt; a) &lt;*&gt; (m &lt;&lt;.&gt;&gt; b)  -- dist
--   </pre>
class (Applicative f, LActionF m f) => DistributiveF m f

-- | The twisted functor is essentially a generalisation of semi-direct
--   product to applicative functors.
data TwistRF f m a
TwistRF :: f a -> !m -> TwistRF f m a

-- | Get the underlying functor value.
twistFunctorValue :: TwistRF f m a -> f a

-- | Get the underlying monoid value.
twistMonoidValue :: TwistRF f m a -> m

-- | A field on the space is a function from the points in the space to
--   some value. Here we define it for a general arrow.
type FieldA arrow = WrappedArrow arrow

-- | A monadic arrow field.
type FieldM monad = FieldA (Kleisli monad)

-- | A field where the underlying arrow is the (-&gt;). This is normally
--   what we call a field.
type Field = FieldA (->)

-- | Compute the value of a field at a given point in the space.
computeField :: Field space b -> space -> b

-- | Runs a monadic field at a given point in the space.
runFieldM :: FieldM monad space b -> space -> monad b

-- | Lift a monadic action to FieldM.
liftToFieldM :: (a -> m b) -> FieldM m a b
instance GHC.Base.Functor f => GHC.Base.Functor (Raaz.Core.MonoidalAction.TwistRF f m)
instance Raaz.Core.MonoidalAction.DistributiveF m f => GHC.Base.Applicative (Raaz.Core.MonoidalAction.TwistRF f m)
instance (Control.Arrow.Arrow arrow, Raaz.Core.MonoidalAction.LAction m space) => Raaz.Core.MonoidalAction.DistributiveF m (Control.Applicative.WrappedArrow arrow space)
instance Raaz.Core.MonoidalAction.Distributive m space => GHC.Base.Semigroup (Raaz.Core.MonoidalAction.SemiR space m)
instance Raaz.Core.MonoidalAction.Distributive m space => GHC.Base.Monoid (Raaz.Core.MonoidalAction.SemiR space m)
instance (Control.Arrow.Arrow arrow, Raaz.Core.MonoidalAction.LAction m space) => Raaz.Core.MonoidalAction.LActionF m (Control.Applicative.WrappedArrow arrow space)


-- | Some useful utility functions and combinators.
module Raaz.Core.Util

-- | A typesafe length for Bytestring
length :: ByteString -> BYTES Int

-- | A type safe version of replicate
replicate :: LengthUnit l => l -> Word8 -> ByteString

-- | Get the value from the bytestring using <a>peek</a>.
fromByteStringStorable :: Storable k => ByteString -> k

-- | The action <tt>create l act</tt> creates a length <tt>l</tt>
--   bytestring where the contents are filled using the the <tt>act</tt> to
--   fill the buffer.
create :: LengthUnit l => l -> (Pointer -> IO ()) -> IO ByteString

-- | The IO action <tt>createFrom n cptr</tt> creates a bytestring by
--   copying <tt>n</tt> bytes from the pointer <tt>cptr</tt>.
createFrom :: LengthUnit l => l -> Pointer -> IO ByteString

-- | Works directly on the pointer associated with the <a>ByteString</a>.
--   This function should only read and not modify the contents of the
--   pointer.
withByteString :: ByteString -> (Pointer -> IO a) -> IO a

-- | Copy the bytestring to the crypto buffer. This operation leads to
--   undefined behaviour if the crypto pointer points to an area smaller
--   than the size of the byte string.
unsafeCopyToPointer :: ByteString -> Pointer -> IO ()

-- | Similar to <a>unsafeCopyToPointer</a> but takes an additional input
--   <tt>n</tt> which is the number of bytes (expressed in type safe length
--   units) to transfer. This operation leads to undefined behaviour if
--   either the bytestring is shorter than <tt>n</tt> or the crypto pointer
--   points to an area smaller than <tt>n</tt>.
unsafeNCopyToPointer :: LengthUnit n => n -> ByteString -> Pointer -> IO ()


-- | An applicative version of parser. This provides a restricted parser
--   which has only an applicative instance.
module Raaz.Core.Parse.Applicative

-- | An applicative parser type for reading data from a pointer.
type Parser = TwistRF ParseAction BytesMonoid

-- | Return the bytes that this parser will read.
parseWidth :: Parser a -> BYTES Int

-- | A parser that fails with a given error message.
parseError :: String -> Parser a

-- | Runs a parser on a byte string. It returns <a>Nothing</a> if the byte
--   string is smaller than what the parser would consume.
runParser :: Parser a -> ByteString -> Maybe a

-- | Run the parser without checking the length constraints.
unsafeRunParser :: Parser a -> Pointer -> IO a

-- | Parse a crypto value. Endian safety is take into account here. This is
--   what you would need when you parse packets from an external source.
--   You can also use this to define the <a>load</a> function in a
--   complicated <a>EndianStore</a> instance.
parse :: EndianStore a => Parser a

-- | Parses a value which is an instance of Storable. Beware that this
--   parser expects that the value is stored in machine endian. Mostly it
--   is useful in defining the <a>peek</a> function in a complicated
--   <a>Storable</a> instance.
parseStorable :: Storable a => Parser a

-- | Parses a vector of elements. It takes care of the correct endian
--   conversion. This is the function to use while parsing external data.
parseVector :: (EndianStore a, Vector v a) => Int -> Parser (v a)

-- | Similar to <a>parseVector</a> but parses according to the host endian.
--   This function is essentially used to define storable instances of
--   complicated data. It is unlikely to be of use when parsing externally
--   serialised data as one would want to keep track of the endianness of
--   the data.
parseStorableVector :: (Storable a, Vector v a) => Int -> Parser (v a)

-- | Similar to <tt>parseVector</tt> but is expected to be slightly faster.
--   It does not check whether the length parameter is non-negative and
--   hence is unsafe. Use it only if you can prove that the length
--   parameter is non-negative.
unsafeParseVector :: (EndianStore a, Vector v a) => Int -> Parser (v a)

-- | Similar to <tt>parseStorableVector</tt> but is expected to be slightly
--   faster. It does not check whether the length parameter is non-negative
--   and hence is unsafe. Use it only if you can prove that the length
--   parameter is non-negative.
unsafeParseStorableVector :: (Storable a, Vector v a) => Int -> Parser (v a)

-- | Parses a strict bytestring of a given length.
parseByteString :: LengthUnit l => l -> Parser ByteString

-- | Skip over some data.
skip :: LengthUnit u => u -> Parser ()


-- | Encoding and decoding values to formats.
module Raaz.Core.Encode

-- | The type class <a>Encodable</a> captures all the types that can be
--   encoded into a stream of bytes. For a user defined type say
--   <tt>Foo</tt>, defining an instance <a>Encodable</a> is all that is
--   required to make use of <tt>encode</tt> and <tt>decode</tt> for any of
--   the supported encoding formats (i.e. instances of the class
--   <a>Format</a>).
--   
--   Minimum complete definition for this class is <a>toByteString</a> and
--   <a>fromByteString</a>. Instances of <a>EndianStore</a> have default
--   definitions for both these functions and hence a trivial instance
--   declaration is sufficient for such types.
--   
--   <pre>
--   newtype Foo = Foo (LE Word64) deriving (Storable, EndianStore)
--   
--   instance EndianStore Foo where
--     ...
--   
--   instance Encodable Foo
--   </pre>
--   
--   In particular, all the endian encoded versions of Haskell's word, i.e
--   types like <tt><a>LE</a> Word32</tt>, <tt><a>LE</a> Word64</tt> etc,
--   are instances of <a>Encodable</a>. Note that the corresponding plain
--   type is <i>not</i> an instance of <a>Encodable</a> because encoding of
--   say <a>Word32</a> without specifying whether the endianness is
--   meaningless.
class Encodable a

-- | Convert stuff to bytestring
toByteString :: Encodable a => a -> ByteString

-- | Try parsing back a value. Returns nothing on failure.
fromByteString :: Encodable a => ByteString -> Maybe a

-- | Unsafe version of <a>fromByteString</a>
unsafeFromByteString :: Encodable a => ByteString -> a

-- | Convert stuff to bytestring
toByteString :: (Encodable a, EndianStore a) => a -> ByteString

-- | Try parsing back a value. Returns nothing on failure.
fromByteString :: (Encodable a, EndianStore a) => ByteString -> Maybe a

-- | A binary format is a representation of binary data often in printable
--   form. We distinguish between various binary formats at the type level
--   and each supported format corresponds to an instance of the the class
--   <a>Format</a>. The <a>encodeByteString</a> and <a>decodeFormat</a> are
--   required to satisfy the laws
--   
--   <pre>
--   decodeFormat . encodeByteString = id
--   </pre>
--   
--   For type safety, the formats themselves are opaque types and hence it
--   is not possible to obtain the underlying binary data directly. We
--   require binary formats to be instances of the class <a>Encodable</a>,
--   with the combinators <a>toByteString</a> and <a>fromByteString</a> of
--   the <a>Encodable</a> class performing the actual encoding and
--   decoding.
--   
--   Instances of <a>Format</a> are required to be instances of <a>Show</a>
--   and so that the encoded format can be easily printed. They are also
--   required to be instances of <a>IsString</a> so that they can be easily
--   represented in Haskell source using the <tt>OverloadedStrings</tt>
--   extension. However, be careful when using this due to the fact that
--   invalid encodings can lead to runtime errors.
class (IsString fmt, Show fmt, Encodable fmt) => Format fmt

-- | Encode binary data into the format. The return type gurantees that any
--   binary data can indeed be encoded into a format.
encodeByteString :: Format fmt => ByteString -> fmt

-- | Decode the format to its associated binary representation. Notice that
--   this function always succeeds: we assume that elements of the type
--   <tt>fmt</tt> are valid encodings and hence the return type is
--   <a>ByteString</a> instead of <tt><a>Maybe</a> ByteString</tt>.
decodeFormat :: Format fmt => fmt -> ByteString

-- | Encode in a given format.
encode :: (Encodable a, Format fmt) => a -> fmt

-- | Decode from a given format. It results in Nothing if there is a parse
--   error.
decode :: (Format fmt, Encodable a) => fmt -> Maybe a

-- | Translate from one format to another.
translate :: (Format fmt1, Format fmt2) => fmt1 -> fmt2

-- | The unsafe version of <a>decode</a>.
unsafeDecode :: (Format fmt, Encodable a) => fmt -> a

-- | The type corresponding to base-16 or hexadecimal encoding. The
--   <a>Base16</a> encoding has a special place in this library: most
--   cryptographic types use <a>Base16</a> encoding for their <a>Show</a>
--   and <a>IsString</a> instance. The combinators <a>fromBase16</a> and
--   <a>showBase16</a> are exposed mainly to make these definitions easy.
data Base16

-- | Base16 variant of <a>fromString</a>. Useful in definition of
--   <a>IsString</a> instances as well as in cases where the default
--   <a>IsString</a> instance does not parse from a base16 encoding.
fromBase16 :: Encodable a => String -> a

-- | Base16 variant of <a>show</a>.
showBase16 :: Encodable a => a -> String

-- | The type corresponding to the standard padded base-64 binary encoding.
data Base64


-- | Module to reading from and writing into buffers.
module Raaz.Core.Transfer

-- | The <a>ReadM</a> is the type that captures the act of reading from a
--   buffer and possibly doing some action on the bytes read. Although
--   inaccurate, it is helpful to think of elements of <a>ReadM</a> as
--   action that on an input buffer transfers data from it to some
--   unspecified source.
--   
--   Read actions form a monoid with the following semantics: if
--   <tt>r1</tt> and <tt>r2</tt> are two read actions then <tt>r1
--   <a>&lt;&gt;</a> r2</tt> first reads the data associated from
--   <tt>r1</tt> and then the read associated with the data <tt>r2</tt>.
data ReadM m

-- | A read io-action.
type ReadIO = ReadM IO

-- | The expression <tt>bytesToRead r</tt> gives the total number of bytes
--   that would be read from the input buffer if the action <tt>r</tt> is
--   performed.
bytesToRead :: ReadM m -> BYTES Int

-- | The action <tt>unsafeRead r ptr</tt> results in reading
--   <tt>bytesToRead r</tt> bytes from the buffer pointed by <tt>ptr</tt>.
--   This action is unsafe as it will not (and cannot) check if the action
--   reads beyond what is legally stored at <tt>ptr</tt>.
unsafeRead :: ReadM m -> Pointer -> m ()

-- | The action <tt>readBytes sz dptr</tt> gives a read action, which if
--   run on an input buffer, will transfers <tt>sz</tt> to the destination
--   buffer pointed by <tt>dptr</tt>. Note that it is the responsibility of
--   the user to make sure that <tt>dptr</tt> has enough space to receive
--   <tt>sz</tt> units of data if and when the read action is executed.
readBytes :: (LengthUnit sz, MonadIO m) => sz -> Dest Pointer -> ReadM m

-- | The action <tt>readInto n dptr</tt> gives a read action which if run
--   on an input buffer, will transfers <tt>n</tt> elements of type
--   <tt>a</tt> into the buffer pointed by <tt>dptr</tt>. In particular,
--   the read action <tt>readInto n dptr</tt> is the same as <tt>readBytes
--   (fromIntegral n :: BYTES Int) dptr</tt> when the type <tt>a</tt> is
--   <a>Word8</a>.
readInto :: (EndianStore a, MonadIO m) => Int -> Dest (Ptr a) -> ReadM m

-- | An element of type `WriteM m` is an action which when executed
--   transfers bytes <i>into</i> its input buffer. The type
--   <tt><a>WriteM</a> m</tt> forms a monoid and hence can be concatnated
--   using the <a>&lt;&gt;</a> operator.
data WriteM m

-- | A write io-action.
type WriteIO = WriteM IO

-- | Returns the bytes that will be written when the write action is
--   performed.
bytesToWrite :: WriteM m -> BYTES Int

-- | Perform the write action without any checks of the buffer
unsafeWrite :: WriteM m -> Pointer -> m ()

-- | The expression <tt><a>write</a> a</tt> gives a write action that
--   stores a value <tt>a</tt>. One needs the type of the value <tt>a</tt>
--   to be an instance of <a>EndianStore</a>. Proper endian conversion is
--   done irrespective of what the machine endianness is. The man use of
--   this write is to serialize data for the consumption of the outside
--   world.
write :: (MonadIO m, EndianStore a) => a -> WriteM m

-- | The expression <tt><a>writeStorable</a> a</tt> gives a write action
--   that stores a value <tt>a</tt> in machine endian. The type of the
--   value <tt>a</tt> has to be an instance of <a>Storable</a>. This should
--   be used when we want to talk with C functions and not when talking to
--   the outside world (otherwise this could lead to endian confusion). To
--   take care of endianness use the <a>write</a> combinator.
writeStorable :: (MonadIO m, Storable a) => a -> WriteM m

-- | The vector version of <a>write</a>.
writeVector :: (EndianStore a, Vector v a, MonadIO m) => v a -> WriteM m

-- | The vector version of <a>writeStorable</a>.
writeStorableVector :: (Storable a, Vector v a, MonadIO m) => v a -> WriteM m

-- | Write many elements from the given buffer
writeFrom :: (MonadIO m, EndianStore a) => Int -> Src (Ptr a) -> WriteM m

-- | The combinator <tt>writeBytes n b</tt> writes <tt>b</tt> as the next
--   <tt>n</tt> consecutive bytes.
writeBytes :: (LengthUnit n, MonadIO m) => Word8 -> n -> WriteM m

-- | The write action <tt>padWrite w n wr</tt> is wr padded with the byte
--   <tt>w</tt> so that the total length ends at a multiple of <tt>n</tt>.
padWrite :: (LengthUnit n, MonadIO m) => Word8 -> n -> WriteM m -> WriteM m

-- | The write action <tt>prependWrite w n wr</tt> is wr pre-pended with
--   the byte <tt>w</tt> so that the total length ends at a multiple of
--   <tt>n</tt>.
prependWrite :: (LengthUnit n, MonadIO m) => Word8 -> n -> WriteM m -> WriteM m

-- | The combinator <tt>glueWrites w n hdr ftr</tt> is equivalent to
--   <tt>hdr &lt;&gt; glue &lt;&gt; ftr</tt> where the write <tt>glue</tt>
--   writes as many bytes <tt>w</tt> so that the total length is aligned to
--   the boundary <tt>n</tt>.
glueWrites :: (LengthUnit n, MonadIO m) => Word8 -> n -> WriteM m -> WriteM m -> WriteM m

-- | Writes a strict bytestring.
writeByteString :: MonadIO m => ByteString -> WriteM m

-- | A write action that just skips over the given bytes.
skipWrite :: (LengthUnit u, Monad m) => u -> WriteM m
instance GHC.Base.Monad m => GHC.Base.Monoid (Raaz.Core.Transfer.ReadM m)
instance GHC.Base.Monad m => GHC.Base.Semigroup (Raaz.Core.Transfer.ReadM m)
instance GHC.Base.Monad m => GHC.Base.Monoid (Raaz.Core.Transfer.WriteM m)
instance GHC.Base.Monad m => GHC.Base.Semigroup (Raaz.Core.Transfer.WriteM m)
instance Control.Monad.IO.Class.MonadIO m => Data.String.IsString (Raaz.Core.Transfer.WriteM m)
instance Raaz.Core.Encode.Internal.Encodable (Raaz.Core.Transfer.WriteM GHC.Types.IO)
instance Raaz.Core.MonoidalAction.LAction (Raaz.Core.Types.Pointer.BYTES GHC.Types.Int) (Raaz.Core.Transfer.TransferAction m)
instance GHC.Base.Monad m => Raaz.Core.MonoidalAction.Distributive (Raaz.Core.Types.Pointer.BYTES GHC.Types.Int) (Raaz.Core.Transfer.TransferAction m)
instance GHC.Base.Monad m => GHC.Base.Semigroup (Raaz.Core.Transfer.TransferM m)
instance GHC.Base.Monad m => GHC.Base.Monoid (Raaz.Core.Transfer.TransferM m)


-- | This module exposes some core types used through out the Raaz library.
--   One of the major goals of the raaz cryptographic library is to use the
--   type safety of Haskell to catch some common bugs at compile time.
--   
--   <b>WARNING:</b> If you are just a user of this library, it is unlikely
--   that you will need to import this module. It is only required if you
--   are a developer and want to define a new cryptographic data type.
module Raaz.Core.Types

-- | All types that support timing safe equality are instances of this
--   class.
class Equality a
eq :: Equality a => a -> a -> Result

-- | Check whether two values are equal using the timing safe <a>eq</a>
--   function. Use this function when defining the <a>Eq</a> instance for a
--   Sensitive data type.
(===) :: Equality a => a -> a -> Bool

-- | The result of a comparison. This is an opaque type and the monoid
--   instance essentially takes AND of two comparisons in a timing safe
--   way.
data Result

-- | This class captures types which provides an endian agnostic way of
--   loading from and storing to data buffers. Any multi-byte type that is
--   meant to be serialised to the outside world should be an instance of
--   this class. When defining the <a>load</a>, <a>store</a>,
--   <a>adjustEndian</a> member functions, care should be taken to ensure
--   proper endian conversion.
class Storable w => EndianStore w

-- | The action <tt>store ptr w</tt> stores <tt>w</tt> at the location
--   pointed by <tt>ptr</tt>. Endianness of the type <tt>w</tt> is taken
--   care of when storing. For example, irrespective of the endianness of
--   the machine, <tt>store ptr (0x01020304 :: BE Word32)</tt> will store
--   the bytes <tt>0x01</tt>, <tt>0x02</tt>, <tt>0x03</tt>, <tt>0x04</tt>
--   respectively at locations <tt>ptr</tt>, <tt>ptr +1</tt>,
--   <tt>ptr+2</tt> and <tt>ptr+3</tt>. On the other hand <tt>store ptr
--   (0x01020304 :: LE Word32)</tt> would store <tt>0x04</tt>,
--   <tt>0x03</tt>, <tt>0x02</tt>, <tt>0x01</tt> at the above locations.
store :: EndianStore w => Ptr w -> w -> IO ()

-- | The action <tt>load ptr</tt> loads the value stored at the
--   <tt>ptr</tt>. Like store, it takes care of the endianness of the data
--   type. For example, if <tt>ptr</tt> points to a buffer containing the
--   bytes <tt>0x01</tt>, <tt>0x02</tt>, <tt>0x03</tt>, <tt>0x04</tt>,
--   irrespective of the endianness of the machine, <tt>load ptr :: IO (BE
--   Word32)</tt> will load the vale <tt>0x01020304</tt> of type <tt>BE
--   Word32</tt> and <tt>load ptr :: IO (LE Word32)</tt> will load
--   <tt>0x04030201</tt> of type <tt>LE Word32</tt>.
load :: EndianStore w => Ptr w -> IO w

-- | The action <tt>adjustEndian ptr n</tt> adjusts the encoding of bytes
--   stored at the location <tt>ptr</tt> to conform with the endianness of
--   the underlying data type. For example, assume that <tt>ptr</tt> points
--   to a buffer containing the bytes <tt>0x01 0x02 0x03 0x04</tt>, and we
--   are on a big endian machine, then <tt>adjustEndian (ptr :: Ptr (LE
--   Word32)) 1</tt> will result in <tt>ptr</tt> pointing to the sequence
--   <tt>0x04 0x03 0x02 0x01</tt>. On the other hand if we were on a little
--   endian machine, the sequence should remain the same. In particular,
--   the following equalities should hold.
--   
--   <pre>
--   store ptr w          = poke ptr w &gt;&gt; adjustEndian ptr 1
--   </pre>
--   
--   Similarly the value loaded by <tt>load ptr</tt> should be same as the
--   value returned by <tt>adjustEndian ptr 1 &gt;&gt; peak ptr</tt>,
--   although the former does not change the contents stored at
--   <tt>ptr</tt> where as the latter might does modify the contents
--   pointed by <tt>ptr</tt> if the endianness of the machine and the time
--   do not agree.
--   
--   The action <tt>adjustEndian ptr n &gt;&gt; adjustEndian ptr n </tt>
--   should be equivalent to <tt>return ()</tt>.
adjustEndian :: EndianStore w => Ptr w -> Int -> IO ()

-- | For the type <tt>w</tt>, the action <tt>copyFromBytes dest src n</tt>
--   copies <tt>n</tt>-elements from <tt>src</tt> to <tt>dest</tt>. Copy
--   performed by this combinator accounts for the endianness of the data
--   in <tt>dest</tt> and is therefore <i>not</i> a mere copy of <tt>n *
--   sizeOf(w)</tt> bytes. This action does not modify the <tt>src</tt>
--   pointer in any way.
copyFromBytes :: EndianStore w => Dest (Ptr w) -> Src Pointer -> Int -> IO ()

-- | Similar to <tt>copyFromBytes</tt> but the transfer is done in the
--   other direction. The copy takes care of performing the appropriate
--   endian encoding.
copyToBytes :: EndianStore w => Dest Pointer -> Src (Ptr w) -> Int -> IO ()

-- | Little endian version of the word type <tt>w</tt>
data LE w

-- | Big endian version of the word type <tt>w</tt>
data BE w

-- | Convert to the little endian variant.
littleEndian :: w -> LE w

-- | Convert to the big endian variants.
bigEndian :: w -> BE w

-- | Store the given value at an offset from the crypto pointer. The offset
--   is given in type safe units.
storeAt :: (EndianStore w, LengthUnit offset) => Ptr w -> offset -> w -> IO ()

-- | Store the given value as the <tt>n</tt>-th element of the array
--   pointed by the crypto pointer.
storeAtIndex :: EndianStore w => Ptr w -> Int -> w -> IO ()

-- | Load from a given offset. The offset is given in type safe units.
loadFrom :: (EndianStore w, LengthUnit offset) => Ptr w -> offset -> IO w

-- | Load the <tt>n</tt>-th value of an array pointed by the crypto
--   pointer.
loadFromIndex :: EndianStore w => Ptr w -> Int -> IO w

-- | The pointer type used by all cryptographic library.
type Pointer = Ptr Align

-- | In cryptographic settings, we need to measure pointer offsets and
--   buffer sizes. The smallest of length/offset that we have is bytes
--   measured using the type <a>BYTES</a>. In various other circumstances,
--   it would be more natural to measure these in multiples of bytes. For
--   example, when allocating buffer to use encrypt using a block cipher it
--   makes sense to measure the buffer size in multiples of block of the
--   cipher. Explicit conversion between these length units, while
--   allocating or moving pointers, involves a lot of low level scaling
--   that is also error prone. To avoid these errors due to unit
--   conversions, we distinguish between different length units at the type
--   level. This type class capturing all such types, i.e. types that stand
--   of length units. Allocation functions and pointer arithmetic are
--   generalised to these length units.
--   
--   All instances of a <a>LengthUnit</a> are required to be instances of
--   <a>Monoid</a> where the monoid operation gives these types the natural
--   size/offset addition semantics: i.e. shifting a pointer by offset
--   <tt>a <a>mappend</a> b</tt> is same as shifting it by <tt>a</tt> and
--   then by <tt>b</tt>.
class (Enum u, Monoid u) => LengthUnit u

-- | Express the length units in bytes.
inBytes :: LengthUnit u => u -> BYTES Int

-- | Type safe lengths/offsets in units of bytes.
newtype BYTES a
BYTES :: a -> BYTES a

-- | Type safe lengths/offsets in units of bits.
newtype BITS a
BITS :: a -> BITS a

-- | Express the length units in bits.
inBits :: LengthUnit u => u -> BITS Word64

-- | Compute the size of a storable element.
sizeOf :: Storable a => a -> BYTES Int

-- | Function similar to <a>bytesQuotRem</a> but works with bits instead.
bitsQuotRem :: LengthUnit u => BITS Word64 -> (u, BITS Word64)

-- | A length unit <tt>u</tt> is usually a multiple of bytes. The function
--   <a>bytesQuotRem</a> is like <a>quotRem</a>: the value <tt>byteQuotRem
--   bytes</tt> is a tuple <tt>(x,r)</tt>, where <tt>x</tt> is
--   <tt>bytes</tt> expressed in the unit <tt>u</tt> with <tt>r</tt> being
--   the reminder.
bytesQuotRem :: LengthUnit u => BYTES Int -> (u, BYTES Int)

-- | Function similar to <a>bitsQuotRem</a> but returns only the quotient.
bitsQuot :: LengthUnit u => BITS Word64 -> u

-- | Function similar to <a>bytesQuotRem</a> but returns only the quotient.
bytesQuot :: LengthUnit u => BYTES Int -> u

-- | Express length unit <tt>src</tt> in terms of length unit <tt>dest</tt>
--   rounding upwards.
atLeast :: (LengthUnit src, LengthUnit dest) => src -> dest

-- | Often we want to allocate a buffer of size <tt>l</tt>. We also want to
--   make sure that the buffer starts at an alignment boundary <tt>a</tt>.
--   However, the standard word allocation functions might return a pointer
--   that is not aligned as desired. The <tt>atLeastAligned l a</tt>
--   returns a length <tt>n</tt> such the length <tt>n</tt> is big enough
--   to ensure that there is at least <tt>l</tt> length of valid buffer
--   starting at the next pointer aligned at boundary <tt>a</tt>. If the
--   alignment required in <tt>a</tt> then allocating @l + a - 1 should do
--   the trick.
atLeastAligned :: LengthUnit l => l -> Alignment -> ALIGN

-- | Express length unit <tt>src</tt> in terms of length unit <tt>dest</tt>
--   rounding downwards.
atMost :: (LengthUnit src, LengthUnit dest) => src -> dest

-- | Types to measure alignment in units of bytes.
data Alignment

-- | The default alignment to use is word boundary.
wordAlignment :: Alignment

-- | Type safe length unit that measures offsets in multiples of word
--   length. This length unit can be used if one wants to make sure that
--   all offsets are word aligned.
data ALIGN

-- | Compute the alignment for a storable object.
alignment :: Storable a => a -> Alignment

-- | Align a pointer to the appropriate alignment.
alignPtr :: Ptr a -> Alignment -> Ptr a

-- | Move the given pointer with a specific offset.
movePtr :: LengthUnit l => Ptr a -> l -> Ptr a

-- | Size of the buffer to be allocated to store an element of type
--   <tt>a</tt> so as to guarantee that there exist enough space to store
--   the element after aligning the pointer. If the size of the element is
--   <tt>s</tt> and its alignment is <tt>a</tt> then this quantity is
--   essentially equal to <tt>s + a - 1</tt>. All units measured in word
--   alignment.
alignedSizeOf :: Storable a => a -> ALIGN

-- | Compute the next aligned pointer starting from the given pointer
--   location.
nextAlignedPtr :: Storable a => Ptr a -> Ptr a

-- | Peek the element from the next aligned location.
peekAligned :: Storable a => Ptr a -> IO a

-- | Poke the element from the next aligned location.
pokeAligned :: Storable a => Ptr a -> a -> IO ()

-- | The expression <tt>allocaAligned a l action</tt> allocates a local
--   buffer of length <tt>l</tt> and alignment <tt>a</tt> and passes it on
--   to the IO action <tt>action</tt>. No explicit freeing of the memory is
--   required as the memory is allocated locally and freed once the action
--   finishes. It is better to use this function than
--   <tt><a>allocaBytesAligned</a></tt> as it does type safe scaling and
--   alignment.
allocaAligned :: LengthUnit l => Alignment -> l -> (Pointer -> IO b) -> IO b

-- | This function allocates a chunk of "secure" memory of a given size and
--   runs the action. The memory (1) exists for the duration of the action
--   (2) will not be swapped during that time and (3) will be wiped clean
--   and deallocated when the action terminates either directly or
--   indirectly via errors. While this is mostly secure, there can be
--   strange situations in multi-threaded application where the memory is
--   not wiped out. For example if you run a crypto-sensitive action inside
--   a child thread and the main thread gets exists, then the child thread
--   is killed (due to the demonic nature of haskell threads) immediately
--   and might not give it chance to wipe the memory clean. This is a
--   problem inherent to how the <tt>bracket</tt> combinator works inside a
--   child thread.
--   
--   TODO: File this insecurity in the wiki.
allocaSecureAligned :: LengthUnit l => Alignment -> l -> (Pointer -> IO a) -> IO a

-- | A less general version of <a>allocaAligned</a> where the pointer
--   passed is aligned to word boundary.
allocaBuffer :: LengthUnit l => l -> (Pointer -> IO b) -> IO b

-- | A less general version of <a>allocaSecureAligned</a> where the pointer
--   passed is aligned to word boundary
allocaSecure :: LengthUnit l => l -> (Pointer -> IO b) -> IO b

-- | Creates a memory of given size. It is better to use over
--   <tt><a>mallocBytes</a></tt> as it uses typesafe length.
mallocBuffer :: LengthUnit l => l -> IO Pointer

-- | Sets the given number of Bytes to the specified value.
memset :: (MonadIO m, LengthUnit l) => Pointer -> Word8 -> l -> m ()

-- | Move between pointers.
memmove :: (MonadIO m, LengthUnit l) => Dest Pointer -> Src Pointer -> l -> m ()

-- | Copy between pointers.
memcpy :: (MonadIO m, LengthUnit l) => Dest Pointer -> Src Pointer -> l -> m ()

-- | A version of <a>hGetBuf</a> which works for any type safe length
--   units.
hFillBuf :: LengthUnit bufSize => Handle -> Pointer -> bufSize -> IO (BYTES Int)

-- | A type <tt>w</tt> forced to be aligned to the alignment boundary
--   <tt>alg</tt>
data Aligned (align :: Nat) w

-- | The underlying unAligned value.
unAligned :: Aligned align w -> w

-- | Align the value to 16-byte boundary
aligned16Bytes :: w -> Aligned 16 w

-- | Align the value to 32-byte boundary
aligned32Bytes :: w -> Aligned 32 w

-- | Align the value to 64-byte boundary
aligned64Bytes :: w -> Aligned 64 w

-- | Tuples that encode their length in their types. For tuples, we call
--   the length its dimension.
data Tuple (dim :: Nat) a

-- | Function that returns the dimension of the tuple. The dimension is
--   calculated without inspecting the tuple and hence the term
--   <tt><a>dimension</a> (undefined :: Tuple 5 Int)</tt> will evaluate to
--   5.
--   
--   The constaint on the dimension of the tuple (since base 4.7.0)
type Dimension (dim :: Nat) = KnownNat dim

-- | This combinator returns the dimension of the tuple.
dimension :: Dimension dim => Tuple dim a -> Int

-- | Computes the initial fragment of a tuple. No length needs to be given
--   as it is infered from the types.
initial :: (Unbox a, Dimension dim0) => Tuple dim1 a -> Tuple dim0 a

-- | The <tt>diagonal a</tt> gives a tuple, all of whose entries is
--   <tt>a</tt>.
diagonal :: (Unbox a, Dimension dim) => a -> Tuple dim a

-- | Construct a tuple by repeating a monadic action.
repeatM :: (Functor m, Monad m, Unbox a, Dimension dim) => m a -> m (Tuple dim a)

-- | A zipwith function for tuples
zipWith :: (Unbox a, Unbox b, Unbox c) => (a -> b -> c) -> Tuple dim a -> Tuple dim b -> Tuple dim c

-- | Construct a tuple out of the list. This function is unsafe and will
--   result in run time error if the list is not of the correct dimension.
unsafeFromList :: (Unbox a, Dimension dim) => [a] -> Tuple dim a

-- | The destination of a copy operation.
--   
--   Note to Developers of Raaz: Since the <a>Dest</a> type inherits the
--   Storable instance of the base type, one can use this type in foreign
--   functions.
data Dest a

-- | The source of a copy operation.
data Src a

-- | smart constructor for source
source :: a -> Src a

-- | smart constructor for destionation.
destination :: a -> Dest a

-- | This class captures all types that have some sort of description
--   attached to it.
class Describable d

-- | Short name that describes the object.
name :: Describable d => d -> String

-- | Longer description
description :: Describable d => d -> String


-- | Generic cryptographic block primtives and their implementations. This
--   module exposes low-level generic code used in the raaz system. Most
--   likely, one would not need to stoop so low and it might be better to
--   use a more high level interface.
module Raaz.Core.Primitives

-- | The type class that captures an abstract block cryptographic
--   primitive. Bulk cryptographic primitives like hashes, ciphers etc
--   often acts on blocks of data. The size of the block is captured by the
--   member <a>blockSize</a>.
--   
--   As a library, raaz believes in providing multiple implementations for
--   a given primitive. The associated type <a>Implementation</a> captures
--   implementations of the primitive.
--   
--   For use in production code, the library recommends a particular
--   implementation using the <a>Recommendation</a> class. By default this
--   is the implementation used when no explicit implementation is
--   specified.
class BlockAlgorithm (Implementation p) => Primitive p where {
    
    -- | Associated type that captures an implementation of this primitive.
    type family Implementation p :: *;
}

-- | The block size.
blockSize :: Primitive p => p -> BYTES Int

-- | Implementation of block primitives work on buffers. Often for optimal
--   performance, and in some case for safety, we need restrictions on the
--   size and alignment of the buffer pointer. This type class captures
--   such restrictions.
class Describable a => BlockAlgorithm a

-- | The alignment expected for the buffer pointer.
bufferStartAlignment :: BlockAlgorithm a => a -> Alignment

-- | Some primitives like ciphers have an encryption/decryption key. This
--   type family captures the key associated with a primitive if it has
--   any.
type family Key prim :: *

-- | Primitives that have a recommended implementations.
class Primitive p => Recommendation p

-- | The recommended implementation for the primitive.
recommended :: Recommendation p => p -> Implementation p

-- | Type safe message length in units of blocks of the primitive. When
--   dealing with buffer lengths for a primitive, it is often better to use
--   the type safe units <a>BLOCKS</a>. Functions in the raaz package that
--   take lengths usually allow any type safe length as long as they can be
--   converted to bytes. This can avoid a lot of tedious and error prone
--   length calculations.
data BLOCKS p

-- | The expression <tt>n <a>blocksOf</a> p</tt> specifies the message
--   lengths in units of the block length of the primitive <tt>p</tt>. This
--   expression is sometimes required to make the type checker happy.
blocksOf :: Int -> p -> BLOCKS p

-- | Allocate a buffer a particular implementation of a primitive prim.
--   algorithm <tt>algo</tt>. It ensures that the memory passed is aligned
--   according to the demands of the implementation.
allocBufferFor :: Primitive prim => Implementation prim -> BLOCKS prim -> (Pointer -> IO b) -> IO b
instance GHC.Enum.Enum (Raaz.Core.Primitives.BLOCKS p)
instance GHC.Classes.Ord (Raaz.Core.Primitives.BLOCKS p)
instance GHC.Classes.Eq (Raaz.Core.Primitives.BLOCKS p)
instance GHC.Show.Show (Raaz.Core.Primitives.BLOCKS p)
instance GHC.Base.Semigroup (Raaz.Core.Primitives.BLOCKS p)
instance GHC.Base.Monoid (Raaz.Core.Primitives.BLOCKS p)
instance Raaz.Core.Primitives.Primitive p => Raaz.Core.Types.Pointer.LengthUnit (Raaz.Core.Primitives.BLOCKS p)


-- | The memory subsystem associated with raaz.
--   
--   <b>Warning:</b> This module is pretty low level and should not be
--   needed in typical use cases. Only developers of protocols and
--   primitives might have a reason to look into this module.
module Raaz.Core.Memory

-- | Any cryptographic primitives use memory to store stuff. This class
--   abstracts all types that hold some memory. Cryptographic application
--   often requires securing the memory from being swapped out (think of
--   memory used to store private keys or passwords). This abstraction
--   supports memory securing. If your platform supports memory locking,
--   then securing a memory will prevent the memory from being swapped to
--   the disk. Once secured the memory location is overwritten by nonsense
--   before being freed.
--   
--   While some basic memory elements like <a>MemoryCell</a> are exposed
--   from the library, often we require compound memory objects built out
--   of simpler ones. The <a>Applicative</a> instance of the <a>Alloc</a>
--   can be made use of in such situation to simplify such instance
--   declaration as illustrated in the instance declaration for a pair of
--   memory elements.
--   
--   <pre>
--   instance (Memory ma, Memory mb) =&gt; Memory (ma, mb) where
--   
--      memoryAlloc             = (,) &lt;$&gt; memoryAlloc &lt;*&gt; memoryAlloc
--   
--      unsafeToPointer (ma, _) =  unsafeToPointer ma
--   </pre>
class Memory m

-- | Returns an allocator for this memory.
memoryAlloc :: Memory m => Alloc m

-- | Returns the pointer to the underlying buffer.
unsafeToPointer :: Memory m => m -> Pointer

-- | A memory element that holds nothing.
data VoidMemory

-- | Copy data from a given memory location to the other. The first
--   argument is destionation and the second argument is source to match
--   with the convention followed in memcpy.
copyMemory :: Memory m => Dest m -> Src m -> IO ()

-- | Memories that can be initialised with a pure value. The pure value
--   resides in the Haskell heap and hence can potentially be swapped.
--   Therefore, this class should be avoided if compromising the
--   initialisation value can be dangerous. Consider using
--   <tt>InitialiseableFromBuffer</tt>
class Memory m => Initialisable m v
initialise :: Initialisable m v => v -> MT m ()

-- | Memories from which pure values can be extracted. Once a pure value is
--   extracted,
class Memory m => Extractable m v
extract :: Extractable m v => MT m v

-- | A memory type that can be initialised from a pointer buffer. The
--   initialisation performs a direct copy from the input buffer and hence
--   the chances of the initialisation value ending up in the swap is
--   minimised.
class Memory m => InitialisableFromBuffer m
initialiser :: InitialisableFromBuffer m => m -> ReadM (MT m)

-- | A memory type that can extract bytes into a buffer. The extraction
--   will perform a direct copy and hence the chances of the extracted
--   value ending up in the swap space is minimised.
class Memory m => ExtractableToBuffer m
extractor :: ExtractableToBuffer m => m -> WriteM (MT m)

-- | A memory location to store a value of type having <a>Storable</a>
--   instance.
data MemoryCell a

-- | Work with the underlying pointer of the memory cell. Useful while
--   working with ffi functions.
withCellPointer :: (MemoryThread mT, Storable a) => (Ptr a -> IO b) -> mT (MemoryCell a) b

-- | Get the pointer associated with the given memory cell.
getCellPointer :: (MemoryThread mT, Storable a) => mT (MemoryCell a) (Ptr a)

-- | A class that captures abstract "memory threads". A memory thread can
--   either be run <a>securely</a> or <a>insecurely</a>. Pure IO actions
--   can be run inside a memory thread using the <tt>runIO</tt>. However,
--   the IO action that is being run <i>must not</i> directly or indirectly
--   run a <tt>secure</tt> action ever. In particular, the following code
--   is bad.
--   
--   <pre>
--   -- BAD EXAMPLE: DO NOT USE.
--   runIO $ securely $ foo
--   </pre>
--   
--   On the other hand the following code is fine
--   
--   <pre>
--   runIO $ insecurely $ someMemoryAction
--   </pre>
--   
--   As to why this is dangerous, it has got to do with the fact that
--   <tt>mlock</tt> and <tt>munlock</tt> do not nest correctly. A single
--   <tt>munlock</tt> can unlock multiple calls of <tt>mlock</tt> on the
--   same page. Whether a given <tt>IO</tt> action unlocks memory is
--   difficult to keep track of; for all you know, it might be a FFI call
--   that does an <tt>memunlock</tt>. Hence, currently there is no easy way
--   to enforce this.
class MemoryThread (mT :: * -> * -> *)

-- | Run a memory action with the internal memory allocated from a locked
--   memory buffer. This memory buffer will never be swapped out by the
--   operating system and will be wiped clean before releasing.
--   
--   Memory locking is an expensive operation and usually there would be a
--   limit to how much locked memory can be allocated. Nonetheless, actions
--   that work with sensitive information like passwords should use this to
--   run an memory action.
securely :: (MemoryThread mT, Memory mem) => mT mem a -> IO a

-- | Run a memory action with the internal memory used by the action being
--   allocated from unlocked memory. Use this function when you work with
--   data that is not sensitive to security considerations (for example,
--   when you want to verify checksums of files).
insecurely :: (MemoryThread mT, Memory mem) => mT mem a -> IO a

-- | Lift an actual memory thread.
liftMT :: MemoryThread mT => MT mem a -> mT mem a

-- | Combinator that allows us to run a memory action on a sub-memory
--   element. A sub-memory of <tt>submem</tt> of a memory element
--   <tt>mem</tt> is given by a projection <tt>proj : mem -&gt;
--   submem</tt>. The action <tt>onSubMemory proj</tt> lifts the a memory
--   thread on the sub element to the compound element.
onSubMemory :: MemoryThread mT => (mem -> submem) -> mT submem a -> mT mem a

-- | Perform an IO action inside the memory thread.
doIO :: MemoryThread mT => IO a -> mT mem a

-- | Get the underlying memory element of the memory thread.
getMemory :: MemoryThread mT => mT mem mem

-- | Apply the given function to the value in the cell. For a function
--   <tt>f :: b -&gt; a</tt>, the action <tt>modify f</tt> first extracts a
--   value of type <tt>b</tt> from the memory element, applies <tt>f</tt>
--   to it and puts the result back into the memory.
--   
--   <pre>
--   modify f = do b          &lt;- extract
--                 initialise $  f b
--   </pre>
modify :: (Initialisable mem a, Extractable mem b, MemoryThread mT) => (b -> a) -> mT mem ()

-- | Run a given memory action in the memory thread.
execute :: MemoryThread mT => (mem -> IO a) -> mT mem a

-- | An action of type <tt><a>MT</a> mem a</tt> is an action that uses
--   internally a single memory object of type <tt>mem</tt> and returns a
--   result of type <tt>a</tt>. All the actions are performed on a single
--   memory element and hence the side effects persist. It is analogues to
--   the <tt>ST</tt> monad.
data MT mem a

-- | An IO allocator can be lifted to the memory thread level as follows.
liftPointerAction :: PointerAction IO a b -> PointerAction (MT mem) a b

-- | A memory allocator for the memory type <tt>mem</tt>. The
--   <a>Applicative</a> instance of <tt>Alloc</tt> can be used to build
--   allocations for complicated memory elements from simpler ones.
type Alloc mem = TwistRF AllocField (BYTES Int) mem

-- | Allocates a buffer of size <tt>l</tt> and returns the pointer to it
--   pointer.
pointerAlloc :: LengthUnit l => l -> Alloc Pointer
instance Foreign.Storable.Storable a => Raaz.Core.Memory.Memory (Raaz.Core.Memory.MemoryCell a)
instance Foreign.Storable.Storable a => Raaz.Core.Memory.Initialisable (Raaz.Core.Memory.MemoryCell a) a
instance Foreign.Storable.Storable a => Raaz.Core.Memory.Extractable (Raaz.Core.Memory.MemoryCell a) a
instance Raaz.Core.Types.Endian.EndianStore a => Raaz.Core.Memory.InitialisableFromBuffer (Raaz.Core.Memory.MemoryCell a)
instance Raaz.Core.Types.Endian.EndianStore a => Raaz.Core.Memory.ExtractableToBuffer (Raaz.Core.Memory.MemoryCell a)
instance Raaz.Core.Memory.Memory Raaz.Core.Memory.VoidMemory
instance Raaz.Core.Memory.MemoryThread Raaz.Core.Memory.MT
instance (Raaz.Core.Memory.Memory ma, Raaz.Core.Memory.Memory mb) => Raaz.Core.Memory.Memory (ma, mb)
instance (Raaz.Core.Memory.Memory ma, Raaz.Core.Memory.Memory mb, Raaz.Core.Memory.Memory mc) => Raaz.Core.Memory.Memory (ma, mb, mc)
instance (Raaz.Core.Memory.Memory ma, Raaz.Core.Memory.Memory mb, Raaz.Core.Memory.Memory mc, Raaz.Core.Memory.Memory md) => Raaz.Core.Memory.Memory (ma, mb, mc, md)
instance GHC.Base.Functor (Raaz.Core.Memory.MT mem)
instance GHC.Base.Applicative (Raaz.Core.Memory.MT mem)
instance GHC.Base.Monad (Raaz.Core.Memory.MT mem)
instance Control.Monad.IO.Class.MonadIO (Raaz.Core.Memory.MT mem)


-- | Module define byte sources.
module Raaz.Core.ByteSource

-- | Abstract byte sources. A bytesource is something that you can use to
--   fill a buffer.
--   
--   <b>WARNING:</b> The source is required to return <a>Exhausted</a> in
--   the boundary case where it has exactly the number of bytes requested.
--   In other words, if the source returns <tt>Remaining</tt> on any
--   particular request, there should be at least 1 additional byte left on
--   the source for the next request. Cryptographic block primitives have
--   do certain special processing for the last block and it is required to
--   know whether the last block has been read or not.
class ByteSource src

-- | Fills a buffer from the source.
fillBytes :: ByteSource src => BYTES Int -> src -> Pointer -> IO (FillResult src)

-- | A byte source src is pure if filling from it does not have any other
--   side effect on the state of the byte source. Formally, two different
--   fills form the same source should fill the buffer with the same bytes.
--   This additional constraint on the source helps to <i>purify</i>
--   certain crypto computations like computing the hash or mac of the
--   source. Usualy sources like <a>ByteString</a> etc are pure byte
--   sources. A file handle is a byte source that is <i>not</i> a pure
--   source.
class ByteSource src => PureByteSource src

-- | This type captures the result of a fill operation.
data FillResult a

-- | There is still bytes left.
Remaining :: a -> FillResult a

-- | source exhausted with so much bytes read.
Exhausted :: BYTES Int -> FillResult a

-- | A version of fillBytes that takes type safe lengths as input.
fill :: (LengthUnit len, ByteSource src) => len -> src -> Pointer -> IO (FillResult src)

-- | Process data from a source in chunks of a particular size.
processChunks :: (MonadIO m, LengthUnit chunkSize, ByteSource src) => m a -> (BYTES Int -> m b) -> src -> chunkSize -> Pointer -> m b

-- | Combinator to handle a fill result.
withFillResult :: (a -> b) -> (BYTES Int -> b) -> FillResult a -> b
instance GHC.Classes.Eq a => GHC.Classes.Eq (Raaz.Core.ByteSource.FillResult a)
instance GHC.Show.Show a => GHC.Show.Show (Raaz.Core.ByteSource.FillResult a)
instance Raaz.Core.ByteSource.PureByteSource Data.ByteString.Internal.ByteString
instance Raaz.Core.ByteSource.PureByteSource Data.ByteString.Lazy.Internal.ByteString
instance Raaz.Core.ByteSource.PureByteSource src => Raaz.Core.ByteSource.PureByteSource [src]
instance Raaz.Core.ByteSource.PureByteSource src => Raaz.Core.ByteSource.PureByteSource (GHC.Maybe.Maybe src)
instance Raaz.Core.ByteSource.ByteSource GHC.IO.Handle.Types.Handle
instance Raaz.Core.ByteSource.ByteSource Data.ByteString.Internal.ByteString
instance Raaz.Core.ByteSource.ByteSource Data.ByteString.Lazy.Internal.ByteString
instance Raaz.Core.ByteSource.ByteSource src => Raaz.Core.ByteSource.ByteSource (GHC.Maybe.Maybe src)
instance Raaz.Core.ByteSource.ByteSource src => Raaz.Core.ByteSource.ByteSource [src]
instance GHC.Base.Functor Raaz.Core.ByteSource.FillResult


-- | Core functions, data types and classes of the raaz package.
module Raaz.Core

-- | Typical size of L1 cache. Used for selecting buffer size etc in crypto
--   operations.
l1Cache :: BYTES Int


-- | This module exposes the low-level internal details of ciphers. Do not
--   import this module unless you want to implement a new cipher or give a
--   new implementation of an existing cipher.
module Raaz.Cipher.Internal

-- | Class capturing ciphers. The implementation of this class should give
--   an encryption and decryption algorithm for messages of length which is
--   a multiple of the block size. Needless to say, the encryption and
--   decryption should be inverses of each other for such messages.
class (Primitive cipher, Implementation cipher ~ SomeCipherI cipher, Describable cipher) => Cipher cipher

-- | Block cipher modes.
data CipherMode

-- | Cipher-block chaining
CBC :: CipherMode

-- | Counter
CTR :: CipherMode

-- | The implementation of a block cipher.
data CipherI cipher encMem decMem
CipherI :: String -> String -> (Pointer -> BLOCKS cipher -> MT encMem ()) -> (Pointer -> BLOCKS cipher -> MT decMem ()) -> Alignment -> CipherI cipher encMem decMem
[cipherIName] :: CipherI cipher encMem decMem -> String
[cipherIDescription] :: CipherI cipher encMem decMem -> String

-- | The underlying block encryption function.
[encryptBlocks] :: CipherI cipher encMem decMem -> Pointer -> BLOCKS cipher -> MT encMem ()

-- | The underlying block decryption function.
[decryptBlocks] :: CipherI cipher encMem decMem -> Pointer -> BLOCKS cipher -> MT decMem ()
[cipherStartAlignment] :: CipherI cipher encMem decMem -> Alignment

-- | Some implementation of a block cipher. This type is existentially
--   quantifies over the memory used in the implementation.
data SomeCipherI cipher
SomeCipherI :: CipherI cipher encMem decMem -> SomeCipherI cipher

-- | Class that captures stream ciphers. An instance of <a>StreamCipher</a>
--   should be an instance of <a>Cipher</a>, with the following additional
--   constraints.
--   
--   <ol>
--   <li>The encryption and decryption should be the same algorithm.</li>
--   <li>Encryption/decryption can be applied to a messages of length
--   <tt>l</tt> even if <tt>l</tt> is not a multiple of block length.</li>
--   <li>The encryption of a prefix of a length <tt>l</tt> of a message
--   <tt>m</tt> should be the same as the <tt>l</tt> length prefix of the
--   encryption of <tt>m</tt>.</li>
--   </ol>
--   
--   It is the duty of the implementer of the cipher to ensure that the
--   above conditions are true before declaring an instance of a stream
--   cipher.
class Cipher cipher => StreamCipher cipher

-- | Constructs a <a>CipherI</a> value out of a stream transformation
--   function. Useful in building a Cipher instance of a stream cipher.
makeCipherI :: String -> String -> (Pointer -> BLOCKS prim -> MT mem ()) -> Alignment -> CipherI prim mem mem

-- | Transform a given bytestring using the recommended implementation of a
--   stream cipher.
transform :: (StreamCipher c, Recommendation c) => c -> Key c -> ByteString -> ByteString

-- | Transforms a given bytestring using a stream cipher. We use the
--   transform instead of encrypt/decrypt because for stream ciphers these
--   operations are same.
transform' :: StreamCipher c => c -> Implementation c -> Key c -> ByteString -> ByteString

-- | Encrypt using the recommended implementation. This function is unsafe
--   because it only works correctly when the input <a>ByteString</a> is of
--   length which is a multiple of the block length of the cipher.
unsafeEncrypt :: (Cipher c, Recommendation c) => c -> Key c -> ByteString -> ByteString

-- | Decrypt using the recommended implementation. This function is unsafe
--   because it only works correctly when the input <a>ByteString</a> is of
--   length which is a multiple of the block length of the cipher.
unsafeDecrypt :: (Cipher c, Recommendation c) => c -> Key c -> ByteString -> ByteString

-- | Encrypt the given <a>ByteString</a>. This function is unsafe because
--   it only works correctly when the input <a>ByteString</a> is of length
--   which is a multiple of the block length of the cipher.
unsafeEncrypt' :: Cipher c => c -> Implementation c -> Key c -> ByteString -> ByteString

-- | Decrypts the given <a>ByteString</a>. This function is unsafe because
--   it only works correctly when the input <a>ByteString</a> is of length
--   which is a multiple of the block length of the cipher.
unsafeDecrypt' :: Cipher c => c -> Implementation c -> Key c -> ByteString -> ByteString
instance GHC.Classes.Eq Raaz.Cipher.Internal.CipherMode
instance GHC.Show.Show Raaz.Cipher.Internal.CipherMode
instance Raaz.Core.Types.Describe.Describable (Raaz.Cipher.Internal.SomeCipherI cipher)
instance Raaz.Core.Primitives.BlockAlgorithm (Raaz.Cipher.Internal.SomeCipherI cipher)
instance Raaz.Core.Primitives.BlockAlgorithm (Raaz.Cipher.Internal.CipherI cipher encMem decMem)
instance Raaz.Core.Types.Describe.Describable (Raaz.Cipher.Internal.CipherI cipher encMem decMem)


-- | Portable C implementation of ChaCha20.
module Raaz.Cipher.ChaCha20.Implementation.CPortable

-- | The portable c implementation of chacha20 cipher.
implementation :: SomeCipherI ChaCha20

-- | The chacha20 randomness generator.
chacha20Random :: Pointer -> BLOCKS ChaCha20 -> MT ChaCha20Mem ()


-- | The Chacha20 cipher.
module Raaz.Cipher.ChaCha20

-- | The type associated with the ChaCha20 cipher.
data ChaCha20

-- | The chacha20 stream cipher.
chacha20 :: ChaCha20

-- | The key type.
data KEY

-- | The IV for the chacha20
data IV

-- | The counter type for chacha20
data Counter


-- | This module exposes the low-level internal details of cryptographic
--   hashes. Do not import this module unless you want to implement a new
--   hash or give a new implementation of an existing hash.
module Raaz.Hash.Internal

-- | Type class capturing a cryptographic hash.
class (Primitive h, EndianStore h, Encodable h, Eq h, Implementation h ~ SomeHashI h) => Hash h

-- | Cryptographic hashes can be computed for messages that are not a
--   multiple of the block size. This combinator computes the maximum size
--   of padding that can be attached to a message.
additionalPadBlocks :: Hash h => h -> BLOCKS h

-- | Compute the hash of a pure byte source like, <a>ByteString</a>.
hash :: (Hash h, Recommendation h, PureByteSource src) => src -> h

-- | Compute the hash of file.
hashFile :: (Hash h, Recommendation h) => FilePath -> IO h

-- | Compute the hash of a generic byte source.
hashSource :: (Hash h, Recommendation h, ByteSource src) => src -> IO h

-- | Similar to <a>hash</a> but the user can specify the implementation to
--   use.
hash' :: (PureByteSource src, Hash h) => Implementation h -> src -> h

-- | Similar to hashFile' but the user can specify the implementation to
--   use.
hashFile' :: Hash h => Implementation h -> FilePath -> IO h

-- | Similar to <tt>hashSource</tt> but the user can specify the
--   implementation to use.
hashSource' :: (Hash h, ByteSource src) => Implementation h -> src -> IO h

-- | The Hash implementation. Implementations should ensure the following.
--   
--   <ol>
--   <li>The action <tt>compress impl ptr blks</tt> should only read till
--   the <tt>blks</tt> offset starting at ptr and never write any
--   data.</li>
--   <li>The action <tt>padFinal impl ptr byts</tt> should touch at most
--   <tt>⌈byts/blocksize⌉ + padBlocks</tt> blocks starting at ptr. It
--   should not write anything till the <tt>byts</tt> offset but may write
--   stuff beyond that.</li>
--   </ol>
--   
--   An easy to remember this rule is to remember that computing hash of a
--   payload should not modify the payload.
data HashI h m
HashI :: String -> String -> (Pointer -> BLOCKS h -> MT m ()) -> (Pointer -> BYTES Int -> MT m ()) -> Alignment -> HashI h m
[hashIName] :: HashI h m -> String
[hashIDescription] :: HashI h m -> String

-- | compress the blocks,
[compress] :: HashI h m -> Pointer -> BLOCKS h -> MT m ()

-- | pad and process the final bytes,
[compressFinal] :: HashI h m -> Pointer -> BYTES Int -> MT m ()
[compressStartAlignment] :: HashI h m -> Alignment

-- | Some implementation of a given hash. The existentially quantification
--   allows us freedom to choose the best memory type suitable for each
--   implementations.
data SomeHashI h
SomeHashI :: HashI h m -> SomeHashI h

-- | The constraints that a memory used by a hash implementation should
--   satisfy.
type HashM h m = (Initialisable m (), Extractable m h, Primitive h)

-- | Certain hashes are essentially bit-truncated versions of other hashes.
--   For example, SHA224 is obtained from SHA256 by dropping the last
--   32-bits. This combinator can be used build an implementation of
--   truncated hash from the implementation of its parent hash.
truncatedI :: (BLOCKS htrunc -> BLOCKS h) -> (mtrunc -> m) -> HashI h m -> HashI htrunc mtrunc

-- | Computing cryptographic hashes usually involves chunking the message
--   into blocks and compressing one block at a time. Usually this
--   compression makes use of the hash of the previous block and the length
--   of the message seen so far to compressing the current block. Most
--   implementations therefore need to keep track of only hash and the
--   length of the message seen so. This memory can be used in such
--   situations.
data HashMemory h
HashMemory :: MemoryCell h -> MemoryCell (BITS Word64) -> HashMemory h

-- | Cell to store the hash
[hashCell] :: HashMemory h -> MemoryCell h

-- | Cell to store the length
[messageLengthCell] :: HashMemory h -> MemoryCell (BITS Word64)

-- | Extract the length of the message hashed so far.
extractLength :: MT (HashMemory h) (BITS Word64)

-- | Update the message length by a given amount.
updateLength :: LengthUnit u => u -> MT (HashMemory h) ()

-- | Gives a memory action that completes the hashing procedure with the
--   rest of the source. Useful to compute the hash of a source with some
--   prefix (like in the HMAC procedure).
completeHashing :: (Hash h, ByteSource src, HashM h m) => HashI h m -> src -> MT m h
instance Foreign.Storable.Storable h => Raaz.Core.Memory.Memory (Raaz.Hash.Internal.HashMemory h)
instance Foreign.Storable.Storable h => Raaz.Core.Memory.Initialisable (Raaz.Hash.Internal.HashMemory h) h
instance Foreign.Storable.Storable h => Raaz.Core.Memory.Extractable (Raaz.Hash.Internal.HashMemory h) h
instance Raaz.Core.Types.Describe.Describable (Raaz.Hash.Internal.SomeHashI h)
instance Raaz.Core.Primitives.BlockAlgorithm (Raaz.Hash.Internal.SomeHashI h)
instance Raaz.Core.Primitives.BlockAlgorithm (Raaz.Hash.Internal.HashI h m)
instance Raaz.Core.Types.Describe.Describable (Raaz.Hash.Internal.HashI h m)


-- | The portable C-implementation of SHA1
module Raaz.Hash.Blake2.Implementation.CPortable

-- | The portable C implementation of BLAKE2b.
implementation2b :: Implementation BLAKE2b

-- | The portable C implementation of BLAKE2s.
implementation2s :: Implementation BLAKE2s


-- | This module exposes combinators to compute the BLAKE2b hash and the
--   associated HMAC for some common types.
module Raaz.Hash.Blake2

-- | The BLAKE2b hash type.
type BLAKE2b = BLAKE2 Word2b

-- | The BLAKE2s hash type.
type BLAKE2s = BLAKE2 Word2s

-- | Compute the blake2b hash of an instance of <a>PureByteSource</a>. Use
--   this for computing the sha1 hash of a strict or lazy byte string.
blake2b :: PureByteSource src => src -> BLAKE2b

-- | Compute the blake2b hash of a file.
blake2bFile :: FilePath -> IO BLAKE2b

-- | Compute the blake2b hash of a general byte source.
blake2bSource :: ByteSource src => src -> IO BLAKE2b


-- | The portable C-implementation of SHA1
module Raaz.Hash.Sha1.Implementation.CPortable

-- | The portable C implementation of SHA1.
implementation :: Implementation SHA1


-- | The portable C-implementation of SHA256.
module Raaz.Hash.Sha256.Implementation.CPortable

-- | The portable C implementation of SHA256.
implementation :: Implementation SHA256

-- | The Hash implementation, i.e. <a>HashI</a> associated with the
--   portable C implementation for the hash SHA256. This can be used to
--   define an implementation of truncated hashes like SHA224.
cPortable :: HashI SHA256 (HashMemory SHA256)


-- | The portable C-implementation of SHA224
module Raaz.Hash.Sha224.Implementation.CPortable

-- | The portable C implementation of SHA224.
implementation :: Implementation SHA224
instance Raaz.Core.Memory.Memory Raaz.Hash.Sha224.Implementation.CPortable.SHA224Memory
instance Raaz.Core.Memory.Initialisable Raaz.Hash.Sha224.Implementation.CPortable.SHA224Memory ()
instance Raaz.Core.Memory.Extractable Raaz.Hash.Sha224.Implementation.CPortable.SHA224Memory Raaz.Hash.Sha224.Internal.SHA224


-- | The portable C-implementation of SHA512
module Raaz.Hash.Sha512.Implementation.CPortable

-- | The portable C implementation of SHA512.
implementation :: Implementation SHA512

-- | The Hash implementation, i.e. <a>HashI</a> associated with the
--   portable C implementation for the hash SHA512. This can be used to
--   implement truncated implementation like SHA384.
cPortable :: HashI SHA512 (HashMemory SHA512)


-- | The portable C-implementation of SHA384
module Raaz.Hash.Sha384.Implementation.CPortable

-- | The portable C implementation of SHA384.
implementation :: Implementation SHA384
instance Raaz.Core.Memory.Memory Raaz.Hash.Sha384.Implementation.CPortable.SHA384Memory
instance Raaz.Core.Memory.Initialisable Raaz.Hash.Sha384.Implementation.CPortable.SHA384Memory ()
instance Raaz.Core.Memory.Extractable Raaz.Hash.Sha384.Implementation.CPortable.SHA384Memory Raaz.Hash.Sha384.Internal.SHA384


-- | Interface for cryptographically secure random byte generators.
module Raaz.Random

-- | A batch of actions on the memory element <tt>mem</tt> that uses some
--   randomness.
data RT mem a

-- | The monad for generating cryptographically secure random data.
type RandM = RT VoidMemory

-- | Generate a random byteString.
randomByteString :: LengthUnit l => l -> RT mem ByteString

-- | Generate a random element from an instance of a RandomStorable
--   element.
random :: (RandomStorable a, Memory mem) => RT mem a

-- | Randomise the contents of a memory cell. Equivalent to
--   <tt><a>random</a> &gt;&gt;= liftMT . initialise</tt> but ensures that
--   no data is transferred to unlocked memory.
randomiseCell :: RandomStorable a => RT (MemoryCell a) ()

-- | Instances of <a>Storable</a> which can be randomly generated. It might
--   appear that all instances of the class <a>Storable</a> should be be
--   instances of this class, after all we know the size of the element,
--   why not write that many random bytes. In fact, this module provides an
--   <a>unsafeFillRandomElements</a> which does that. However, we do not
--   give a blanket definition for all storables because for certain
--   refinements of a given type, like for example, Word8's modulo 10,
--   <a>unsafeFillRandomElements</a> introduces unacceptable skews.
class Storable a => RandomStorable a

-- | Fill the buffer with so many random elements of type a.
fillRandomElements :: (RandomStorable a, Memory mem) => Int -> Ptr a -> RT mem ()

-- | This is a helper function that has been exported to simplify the
--   definition of a <a>RandomStorable</a> instance for <a>Storable</a>
--   types. However, there is a reason why we do not give a blanket
--   instance for all instances <a>Storable</a> and why this function is
--   unsafe? This function generates a random element of type <tt>a</tt> by
--   generating <tt>n</tt> random bytes where <tt>n</tt> is the size of the
--   elements of <tt>a</tt>. For instances that range the entire <tt>n</tt>
--   byte space this is fine. However, if the type is actually a refinement
--   of such a type, (consider a <tt><a>Word8</a></tt> modulo <tt>10</tt>
--   for example) this function generates an unacceptable skew in the
--   distribution. Hence this function is prefixed unsafe.
unsafeFillRandomElements :: (Memory mem, Storable a) => Int -> Ptr a -> RT mem ()

-- | Fill the given input pointer with random bytes.
fillRandomBytes :: LengthUnit l => l -> Pointer -> RT mem ()

-- | Reseed from the system entropy pool. There is never a need to
--   explicitly seed your generator. The insecurely and securely calls
--   makes sure that your generator is seed before starting. Furthermore,
--   the generator also reseeds after every few GB of random bytes that it
--   generates. Generating random data from the system entropy is usually
--   an order of magnitude slower than using a fast stream cipher.
--   Reseeding often can slow your program considerably without any
--   additional security advantage.
reseed :: RT mem ()
instance Control.Monad.IO.Class.MonadIO (Raaz.Random.RT mem)
instance GHC.Base.Monad (Raaz.Random.RT mem)
instance GHC.Base.Applicative (Raaz.Random.RT mem)
instance GHC.Base.Functor (Raaz.Random.RT mem)
instance Raaz.Random.RandomStorable GHC.Word.Word8
instance Raaz.Random.RandomStorable GHC.Word.Word16
instance Raaz.Random.RandomStorable GHC.Word.Word32
instance Raaz.Random.RandomStorable GHC.Word.Word64
instance Raaz.Random.RandomStorable GHC.Types.Word
instance Raaz.Random.RandomStorable GHC.Int.Int8
instance Raaz.Random.RandomStorable GHC.Int.Int16
instance Raaz.Random.RandomStorable GHC.Int.Int32
instance Raaz.Random.RandomStorable GHC.Int.Int64
instance Raaz.Random.RandomStorable GHC.Types.Int
instance Raaz.Random.RandomStorable Raaz.Cipher.ChaCha20.Internal.KEY
instance Raaz.Random.RandomStorable Raaz.Cipher.ChaCha20.Internal.IV
instance Raaz.Random.RandomStorable w => Raaz.Random.RandomStorable (Raaz.Core.Types.Endian.LE w)
instance Raaz.Random.RandomStorable w => Raaz.Random.RandomStorable (Raaz.Core.Types.Endian.BE w)
instance (Raaz.Core.Types.Tuple.Dimension d, Data.Vector.Unboxed.Base.Unbox w, Raaz.Random.RandomStorable w) => Raaz.Random.RandomStorable (Raaz.Core.Types.Tuple.Tuple d w)
instance Raaz.Core.Memory.MemoryThread Raaz.Random.RT


-- | This module exposes combinators to compute the SHA512 hash and the
--   associated HMAC for some common types.
module Raaz.Hash.Sha512

-- | The Sha512 hash value. Used in implementation of Sha384 as well.
data SHA512

-- | Compute the sha512 hash of an instance of <a>PureByteSource</a>. Use
--   this for computing the sha512 hash of a strict or lazy byte string.
sha512 :: PureByteSource src => src -> SHA512

-- | Compute the sha512 hash of a file.
sha512File :: FilePath -> IO SHA512

-- | Compute the sha512 hash of a general byte source.
sha512Source :: ByteSource src => src -> IO SHA512

-- | Compute the message authentication code using hmac-sha512.
hmacSha512 :: PureByteSource src => Key (HMAC SHA512) -> src -> HMAC SHA512

-- | Compute the message authentication code for a file.
hmacSha512File :: Key (HMAC SHA512) -> FilePath -> IO (HMAC SHA512)

-- | Compute the message authetication code for a generic byte source.
hmacSha512Source :: ByteSource src => Key (HMAC SHA512) -> src -> IO (HMAC SHA512)


-- | This module exposes combinators to compute the SHA384 hash and the
--   associated HMAC for some common types.
module Raaz.Hash.Sha384

-- | The Sha384 hash value.
data SHA384

-- | Compute the sha384 hash of an instance of <a>PureByteSource</a>. Use
--   this for computing the sha384 hash of a strict or lazy byte string.
sha384 :: PureByteSource src => src -> SHA384

-- | Compute the sha384 hash of a file.
sha384File :: FilePath -> IO SHA384

-- | Compute the sha384 hash of a general byte source.
sha384Source :: ByteSource src => src -> IO SHA384

-- | Compute the message authentication code using hmac-sha384.
hmacSha384 :: PureByteSource src => Key (HMAC SHA384) -> src -> HMAC SHA384

-- | Compute the message authentication code for a file.
hmacSha384File :: Key (HMAC SHA384) -> FilePath -> IO (HMAC SHA384)

-- | Compute the message authetication code for a generic byte source.
hmacSha384Source :: ByteSource src => Key (HMAC SHA384) -> src -> IO (HMAC SHA384)


-- | This module exposes combinators to compute the SHA256 hash and the
--   associated HMAC for some common types.
module Raaz.Hash.Sha256

-- | The Sha256 hash value.
data SHA256

-- | Compute the sha256 hash of an instance of <a>PureByteSource</a>. Use
--   this for computing the sha256 hash of a strict or lazy byte string.
sha256 :: PureByteSource src => src -> SHA256

-- | Compute the sha256 hash of a file.
sha256File :: FilePath -> IO SHA256

-- | Compute the sha256 hash of a general byte source.
sha256Source :: ByteSource src => src -> IO SHA256

-- | Compute the message authentication code using hmac-sha256.
hmacSha256 :: PureByteSource src => Key (HMAC SHA256) -> src -> HMAC SHA256

-- | Compute the message authentication code for a file.
hmacSha256File :: Key (HMAC SHA256) -> FilePath -> IO (HMAC SHA256)

-- | Compute the message authetication code for a generic byte source.
hmacSha256Source :: ByteSource src => Key (HMAC SHA256) -> src -> IO (HMAC SHA256)


-- | This module exposes combinators to compute the SHA224 hash and the
--   associated HMAC for some common types.
module Raaz.Hash.Sha224

-- | Sha224 hash value which consist of 7 32bit words.
data SHA224

-- | Compute the sha224 hash of an instance of <a>PureByteSource</a>. Use
--   this for computing the sha224 hash of a strict or lazy byte string.
sha224 :: PureByteSource src => src -> SHA224

-- | Compute the sha224 hash of a file.
sha224File :: FilePath -> IO SHA224

-- | Compute the sha224 hash of a general byte source.
sha224Source :: ByteSource src => src -> IO SHA224

-- | Compute the message authentication code using hmac-sha224.
hmacSha224 :: PureByteSource src => Key (HMAC SHA224) -> src -> HMAC SHA224

-- | Compute the message authentication code for a file.
hmacSha224File :: Key (HMAC SHA224) -> FilePath -> IO (HMAC SHA224)

-- | Compute the message authetication code for a generic byte source.
hmacSha224Source :: ByteSource src => Key (HMAC SHA224) -> src -> IO (HMAC SHA224)


-- | This module exposes combinators to compute the SHA1 hash and the
--   associated HMAC for some common types.

-- | <i>Deprecated: SHA1 is broken. This module is here only for
--   transition.</i>
module Raaz.Hash.Sha1

-- | The cryptographic hash SHA1.
data SHA1

-- | Compute the sha1 hash of an instance of <a>PureByteSource</a>. Use
--   this for computing the sha1 hash of a strict or lazy byte string.
sha1 :: PureByteSource src => src -> SHA1

-- | Compute the sha1 hash of a file.
sha1File :: FilePath -> IO SHA1

-- | Compute the sha1 hash of a general byte source.
sha1Source :: ByteSource src => src -> IO SHA1

-- | Compute the message authentication code using hmac-sha1.
hmacSha1 :: PureByteSource src => Key (HMAC SHA1) -> src -> HMAC SHA1

-- | Compute the message authentication code for a file.
hmacSha1File :: Key (HMAC SHA1) -> FilePath -> IO (HMAC SHA1)

-- | Compute the message authetication code for a generic byte source.
hmacSha1Source :: ByteSource src => Key (HMAC SHA1) -> src -> IO (HMAC SHA1)


-- | This module exposes all the cryptographic hash functions available
--   under the raaz library.
module Raaz.Hash

-- | Type class capturing a cryptographic hash.
class (Primitive h, EndianStore h, Encodable h, Eq h, Implementation h ~ SomeHashI h) => Hash h

-- | Compute the hash of a pure byte source like, <a>ByteString</a>.
hash :: (Hash h, Recommendation h, PureByteSource src) => src -> h

-- | Compute the hash of file.
hashFile :: (Hash h, Recommendation h) => FilePath -> IO h

-- | Compute the hash of a generic byte source.
hashSource :: (Hash h, Recommendation h, ByteSource src) => src -> IO h

-- | The HMAC associated to a hash value. The HMAC type is essentially the
--   underlying hash type wrapped inside a newtype. Therefore, the
--   <a>Eq</a> instance for HMAC is essentially the <a>Eq</a> instance for
--   the underlying hash. It is safe against timing attack provided the
--   underlying hash comparison is safe under timing attack.
data HMAC h

-- | Compute the hash of a pure byte source like, <a>ByteString</a>.
hmac :: (Hash h, Recommendation h, PureByteSource src) => Key (HMAC h) -> src -> HMAC h

-- | Compute the hmac of file.
hmacFile :: (Hash h, Recommendation h) => Key (HMAC h) -> FilePath -> IO (HMAC h)

-- | Compute the hmac of a generic byte source.
hmacSource :: (Hash h, Recommendation h, ByteSource src) => Key (HMAC h) -> src -> IO (HMAC h)


-- | Portable C implementation of AES ciphers.
module Raaz.Cipher.AES.CBC.Implementation.CPortable

-- | Implementation of 128-bit AES in CBC mode using Portable C.
aes128cbcI :: Implementation (AES 128 'CBC)

-- | Implementation of 192-bit AES in CBC mode using Portable C.
aes192cbcI :: Implementation (AES 192 'CBC)

-- | Implementation of 256-bit AES in CBC mode using Portable C.
aes256cbcI :: Implementation (AES 256 'CBC)
instance Raaz.Core.Memory.Memory Raaz.Cipher.AES.CBC.Implementation.CPortable.M256
instance Raaz.Core.Memory.Initialisable Raaz.Cipher.AES.CBC.Implementation.CPortable.M256 (Raaz.Cipher.AES.Internal.KEY256, Raaz.Cipher.AES.Internal.IV)
instance Raaz.Core.Memory.Memory Raaz.Cipher.AES.CBC.Implementation.CPortable.M192
instance Raaz.Core.Memory.Initialisable Raaz.Cipher.AES.CBC.Implementation.CPortable.M192 (Raaz.Cipher.AES.Internal.KEY192, Raaz.Cipher.AES.Internal.IV)
instance Raaz.Core.Memory.Memory Raaz.Cipher.AES.CBC.Implementation.CPortable.M128
instance Raaz.Core.Memory.Initialisable Raaz.Cipher.AES.CBC.Implementation.CPortable.M128 (Raaz.Cipher.AES.Internal.KEY128, Raaz.Cipher.AES.Internal.IV)


-- | The AES block cipher.
module Raaz.Cipher.AES

-- | The type associated with AES ciphers. Raaz provides AES variants with
--   key lengths 128, 192 and 256. The key types for the above ciphers in
--   cbc mode are given by the types <tt>(<a>KEY128</a>, IV)</tt>,
--   <tt>(<a>KEY192</a>, IV)</tt> <tt>(<a>KEY256</a>, IV)</tt>
--   respectively.
data AES (n :: Nat) (mode :: CipherMode)

-- | Key used for AES-128
data KEY128

-- | Key used for AES-128
data KEY192

-- | Key used for AES-128
data KEY256

-- | The IV used by the CBC mode.
data IV

-- | 128-bit aes cipher in <a>CBC</a> mode.
aes128cbc :: AES 128 'CBC

-- | 128-bit aes cipher in <a>CBC</a> mode.
aes192cbc :: AES 192 'CBC

-- | 128-bit aes cipher in <a>CBC</a> mode.
aes256cbc :: AES 256 'CBC

-- | Smart constructors for AES 128 ctr.
aes128ctr :: AES 128 'CTR


-- | This module exposes all the ciphers provided by raaz. The interface
--   here is pretty low level and it is usually the case that you would not
--   need to work at this level of detail.
module Raaz.Cipher

-- | Class that captures stream ciphers. An instance of <a>StreamCipher</a>
--   should be an instance of <a>Cipher</a>, with the following additional
--   constraints.
--   
--   <ol>
--   <li>The encryption and decryption should be the same algorithm.</li>
--   <li>Encryption/decryption can be applied to a messages of length
--   <tt>l</tt> even if <tt>l</tt> is not a multiple of block length.</li>
--   <li>The encryption of a prefix of a length <tt>l</tt> of a message
--   <tt>m</tt> should be the same as the <tt>l</tt> length prefix of the
--   encryption of <tt>m</tt>.</li>
--   </ol>
--   
--   It is the duty of the implementer of the cipher to ensure that the
--   above conditions are true before declaring an instance of a stream
--   cipher.
class Cipher cipher => StreamCipher cipher

-- | Transform a given bytestring using the recommended implementation of a
--   stream cipher.
transform :: (StreamCipher c, Recommendation c) => c -> Key c -> ByteString -> ByteString

-- | The chacha20 stream cipher.
chacha20 :: ChaCha20

-- | Class capturing ciphers. The implementation of this class should give
--   an encryption and decryption algorithm for messages of length which is
--   a multiple of the block size. Needless to say, the encryption and
--   decryption should be inverses of each other for such messages.
class (Primitive cipher, Implementation cipher ~ SomeCipherI cipher, Describable cipher) => Cipher cipher

-- | 128-bit aes cipher in <a>CBC</a> mode.
aes128cbc :: AES 128 'CBC

-- | 128-bit aes cipher in <a>CBC</a> mode.
aes192cbc :: AES 192 'CBC

-- | 128-bit aes cipher in <a>CBC</a> mode.
aes256cbc :: AES 256 'CBC


-- | This is the top-level module for the Raaz cryptographic library. By
--   importing this module you get a rather high-level access to the
--   primitives provided by the library.
module Raaz

-- | Raaz library version number.
version :: Version
