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


-- | The raaz cryptographic library.
--   
--   Raaz is a cryptographic network library for Haskell designed to use
--   strong typing to eliminate some common errors that occur in
--   cryptographic settings like side channel attacks. This package
--   implements basic types and cryptographic primitives like hashes, macs
--   etc. Actual network protocols are expected to use this library. Common
--   abstractions like for example packet parsing should be part of this
--   library.
@package raaz
@version 0.0.2


-- | This module provides an abstract interface for Diffie Hellman Key
--   Exchange.
module Raaz.Core.DH

-- | The DH (Diffie-Hellman) typeclass provides an interface for key
--   exchanges. <a>Secret</a> represents the secret generated by each party
--   &amp; known only to itself. <a>PublicToken</a> represents the token
--   generated from the <a>Secret</a> which is sent to the other party.
--   <a>SharedSecret</a> represents the common secret generated by both
--   parties from the respective public tokens. <a>publicToken</a> takes
--   the generator of the group and a secret and generates the public
--   token. <a>sharedSecret</a> takes the generator of the group, secret of
--   one party and public token of the other party and generates the shared
--   secret.
class DH d where type Secret d :: * type PublicToken d :: * type SharedSecret d :: * where {
    type family Secret d :: *;
    type family PublicToken d :: *;
    type family SharedSecret d :: *;
}
publicToken :: DH d => d -> Secret d -> PublicToken d
sharedSecret :: DH d => d -> Secret d -> PublicToken d -> SharedSecret d


-- | 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

-- | 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

-- | 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 :: Monad m => (a -> m b) -> FieldM m a b
instance Raaz.Core.MonoidalAction.Distributive m space => GHC.Base.Monoid (Raaz.Core.MonoidalAction.SemiR space m)
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.LActionF m (Control.Applicative.WrappedArrow arrow space)
instance (Control.Arrow.Arrow arrow, Raaz.Core.MonoidalAction.LAction m space) => Raaz.Core.MonoidalAction.DistributiveF m (Control.Applicative.WrappedArrow arrow space)


-- | 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

-- | 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


-- | 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 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 ()

module Raaz.Core.Encode

-- | The type class <a>Encodable</a> captures all the types that can be
--   encoded into a stream of bytes. By making a type say <tt>Foo</tt> an
--   instance of the <a>Encodable</a> class, we get for free methods to
--   encode it in any of the supported 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>
--   instance Encodable Foo
--   </pre>
class Encodable a where toByteString w = unsafeCreate (sizeOf w) putit where putit ptr = store (castPtr ptr) w fromByteString bs | byteSize proxy == length bs = Just w | otherwise = Nothing where w = unsafePerformIO $ withByteString bs (load . castPtr) proxy = undefined `asTypeOf` w unsafeFromByteString = fromMaybe (error "fromByteString error") . fromByteString

-- | 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 write stuff to buffers. As opposed to similar functions
--   exposed in <a>Raaz.Core.Write.Unsafe</a>, the writes exposed here are
--   safe as necessary range checks are done on the buffer before writing
--   stuff to it.
module Raaz.Core.Write

-- | A write is an action which when executed using <tt>runWrite</tt>
--   writes bytes to the input buffer. It is similar to the <a>Write</a>
--   type exposed from the <a>Raaz.Write.Unsafe</a> module except that it
--   keeps track of the total bytes that would be written to the buffer if
--   the action is run. The <tt>runWrite</tt> action will raise an error if
--   the buffer it is provided with is of size smaller. <a>Write</a>s are
--   monoid and hence can be concatnated using the <a>&lt;&gt;</a>
--   operator.
type Write = SemiR WriteAction BytesMonoid

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

-- | Perform the write action without any checks.
unsafeWrite :: Write -> Pointer -> IO ()

-- | 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 :: EndianStore a => a -> Write

-- | 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 :: Storable a => a -> Write

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

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

-- | The combinator <tt>writeBytes n b</tt> writes <tt>b</tt> as the next
--   <tt>n</tt> consecutive bytes.
writeBytes :: LengthUnit n => Word8 -> n -> Write

-- | Writes a strict bytestring.
writeByteString :: ByteString -> Write

-- | A write action that just skips over the given bytes.
skipWrite :: LengthUnit u => u -> Write
instance GHC.Base.Monoid Raaz.Core.Write.WriteM
instance Raaz.Core.MonoidalAction.LAction Raaz.Core.Write.BytesMonoid Raaz.Core.Write.WriteAction
instance Raaz.Core.MonoidalAction.Distributive Raaz.Core.Write.BytesMonoid Raaz.Core.Write.WriteAction
instance Data.String.IsString Raaz.Core.Write.Write
instance Raaz.Core.Encode.Internal.Encodable Raaz.Core.Write.Write


-- | This module exposes some core types used through out the Raaz library.
--   One of the major goals of the raaz cryptographic library use the type
--   safety of Haskell to catch some common bugs at compile time. As of now
--   we address three kinds of errors
module Raaz.Core.Types

-- | In a cryptographic setting, naive equality checking is dangerous. This
--   class is the timing safe way of doing equality checking. The
--   recommended method of defining equality checking for cryptographically
--   sensitive data is as follows.
--   
--   <ol>
--   <li>Define an instance of <a>Equality</a>.</li>
--   <li>Make use of the above instance to define <a>Eq</a> instance as
--   follows.</li>
--   </ol>
--   
--   <pre>
--   data SomeSensitiveType = ...
--   
--   instance Equality SomeSensitiveType where
--            eq a b = ...
--   
--   instance Eq SomeSensitiveType where
--        (==) a b = a === b
--   </pre>
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

-- | Timing independent equality checks for vector of values. <i>Do not</i>
--   use this to check the equality of two general vectors in a timing
--   independent manner (use <a>eqVector</a> instead) because:
--   
--   <ol>
--   <li>They do not work for vectors of unequal lengths,</li>
--   <li>They do not work for empty vectors.</li>
--   </ol>
--   
--   The use case is for defining equality of data types which have fixed
--   size vector quantities in it. Like for example
--   
--   <pre>
--   import Data.Vector.Unboxed
--   newtype Sha1 = Sha1 (Vector (BE Word32))
--   
--   instance Eq Sha1 where
--      (==) (Sha1 g) (Sha1 h) = oftenCorrectEqVector g h
--   </pre>
oftenCorrectEqVector :: (Vector v a, Equality a, Vector v Result) => v a -> v a -> Bool

-- | Timing independent equality checks for vectors. If you know that the
--   vectors are not empty and of equal length, you may use the slightly
--   faster <a>oftenCorrectEqVector</a>
eqVector :: (Vector v a, Equality a, Vector v Result) => v a -> v a -> Bool

-- | This class is the starting point of an endian agnostic interface to
--   basic cryptographic data types. Endianness only matters when we first
--   load the data from the buffer or when we finally write the data out.
--   Any multi-byte type that are meant to be serialised should define and
--   instance of this class. The <a>load</a> and <a>store</a> should takes
--   care of the appropriate endian conversion.
class Storable w => EndianStore w

-- | Store the given value at the locating pointed by the pointer
store :: EndianStore w => Pointer -> w -> IO ()

-- | Load the value from the location pointed by the pointer.
load :: EndianStore w => Pointer -> IO w

-- | 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) => Pointer -> 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 => Pointer -> Int -> w -> IO ()

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

-- | Load the <tt>n</tt>-th value of an array pointed by the crypto
--   pointer.
loadFromIndex :: EndianStore w => Pointer -> 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 in different units. To avoid errors due to unit
--   conversions, we distinguish between different length units at the type
--   level. This type class capturing such types, i.e. types that stand of
--   length units.
class (Num u, Enum u) => LengthUnit u

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

-- | 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
data ALIGN

-- | A type whose only purpose in this universe is to provide alignment
--   safe pointers.
data Align

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

-- | 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

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

-- | The expression <tt>allocaBuffer l action</tt> allocates a local buffer
--   of length <tt>l</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>allocaBytes</a></tt> as it
--   does type safe scaling. This function also ensure that the allocated
--   buffer is word aligned.
allocaBuffer :: LengthUnit l => 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.
allocaSecure :: LengthUnit l => l -> (Pointer -> IO a) -> IO a

-- | 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

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

-- | Similar to <a>sizeOf</a> but returns the length in type safe units.
byteSize :: Storable a => a -> BYTES Int

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

-- | Move between pointers.
memmove :: LengthUnit l => Pointer -> Pointer -> l -> IO ()

-- | Copy between pointers.
memcpy :: LengthUnit l => Pointer -> Pointer -> l -> IO ()

-- | 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.
dimension :: (Unbox a, KnownNat 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, KnownNat dim0, KnownNat dim1) => Tuple dim1 a -> Tuple dim0 a

-- | 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, KnownNat dim) => [a] -> Tuple dim 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


-- | The memory subsystem associated with raaz.
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
--   
--      underlyingPtr (ma, _) =  underlyingPtr ma
--   </pre>
class Memory m

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

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

-- | 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 => m -> m -> IO ()

-- | A memory location to store a value of type having <a>Storable</a>
--   instance.
data MemoryCell a
class Memory m => Initialisable m v
initialise :: Initialisable m v => v -> MT m ()
class Memory m => Extractable m v
extract :: Extractable m v => MT m v

-- | An action of type <tt><a>MT</a> mem a</tt> is an action that uses
--   internally a 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

-- | Run a given memory action in the memory thread.
execute :: (mem -> IO a) -> MT mem a
getMemory :: MT mem mem

-- | Compound memory elements might intern be composed of sub-elements.
--   Often one might want to <i>lift</i> the memory thread for a
--   sub-element to the compound element. Given a sub-element of type
--   <tt>mem'</tt> which can be obtained from the compound memory element
--   of type <tt>mem</tt> using the projection <tt>proj</tt>, <tt>liftSubMT
--   proj</tt> lifts the a memory thread of the sub element to the compound
--   element.
liftSubMT :: (mem -> mem') -> MT mem' a -> MT mem a

-- | 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 m a, Extractable m b) => (b -> a) -> MT m ()

-- | Get the pointer associated with the given memory.
getMemoryPointer :: Memory mem => MT mem Pointer

-- | Work with the underlying pointer of the memory element. Useful while
--   working with ffi functions.
withPointer :: Memory mem => (Pointer -> IO b) -> MT mem b

-- | Given an memory thread
allocate :: LengthUnit bufSize => bufSize -> (Pointer -> MT mem a) -> MT mem a

-- | A class that captures monads that use an internal memory element.
--   
--   Any instance of <a>MonadMemory</a> can be executed <a>securely</a> in
--   which case all allocations are performed from a locked pool of memory.
--   which at the end of the operation is also wiped clean before
--   deallocation.
--   
--   Systems often put tight restriction on the amount of memory a process
--   can lock. Therefore, secure memory is often to be used judiciously.
--   Instances of this class <i>should</i> also implement the the
--   combinator <a>insecurely</a> which allocates all memory from an
--   unlocked memory pool.
--   
--   This library exposes two instances of <a>MonadMemory</a>
--   
--   <ol>
--   <li><i>Memory threads</i> captured by the type <a>MT</a>, which are a
--   sequence of actions that use the same memory element and</li>
--   <li><i>Memory actions</i> captured by the type <a>MemoryM</a>.</li>
--   </ol>
--   
--   <i>WARNING:</i> Be careful with <a>liftIO</a>.
--   
--   The rule of thumb to follow is that the action being lifted should
--   itself never unlock any memory. In particular, the following code is
--   bad because the <a>securely</a> action unlocks some portion of the
--   memory after <tt>foo</tt> is executed.
--   
--   <pre>
--   liftIO $ securely $ foo
--   </pre>
--   
--   On the other hand the following code is fine
--   
--   <pre>
--   liftIO $ insecurely $ someMemoryAction
--   </pre>
--   
--   Whether an <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>.
--   
--   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.
class (Monad m, MonadIO m) => MonadMemory m

-- | Perform the memory action where all memory elements are allocated
--   locked memory. All memory allocated will be locked and hence will
--   never be swapped out by the operating system. It will also 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 :: MonadMemory m => m a -> IO a

-- | Perform the memory action where all memory elements are allocated
--   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 :: MonadMemory m => m a -> IO a

-- | A memory action that uses some sort of memory element internally.
data MemoryM a

-- | Run the memory thread to obtain a memory action.
runMT :: Memory mem => MT mem a -> MemoryM a

-- | 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 ALIGNMonoid mem

-- | Allocates a buffer of size <tt>l</tt> and returns the pointer to it
--   pointer.
pointerAlloc :: LengthUnit l => l -> Alloc Pointer
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)
instance Raaz.Core.Memory.Memory mem => Raaz.Core.Memory.MonadMemory (Raaz.Core.Memory.MT mem)
instance GHC.Base.Functor Raaz.Core.Memory.MemoryM
instance GHC.Base.Applicative Raaz.Core.Memory.MemoryM
instance GHC.Base.Monad Raaz.Core.Memory.MemoryM
instance Control.Monad.IO.Class.MonadIO Raaz.Core.Memory.MemoryM
instance Raaz.Core.Memory.MonadMemory Raaz.Core.Memory.MemoryM
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 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


-- | 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.
--   
--   There is a <i>reference implementation</i> where the emphasis is on
--   correctness rather than speed or security. They are used to verify the
--   correctness of the other implementations for the same primitive. Apart
--   from this, for production use, we have a recommended implementation.
class (Describable (Implementation p)) => Primitive p where type Implementation p :: * where {
    type family Implementation p :: *;
}

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

-- | A symmetric primitive. An example would be primitives like Ciphers,
--   HMACs etc.
class Primitive prim => Symmetric prim where type Key prim where {
    type family Key prim;
}

-- | An asymmetric primitive.
class Asymmetric prim where type PublicKey prim type PrivateKey prim where {
    type family PublicKey prim;
    type family PrivateKey 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
instance GHC.Real.Integral (Raaz.Core.Primitives.BLOCKS p)
instance GHC.Num.Num (Raaz.Core.Primitives.BLOCKS p)
instance GHC.Real.Real (Raaz.Core.Primitives.BLOCKS p)
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 Raaz.Core.Primitives.Primitive p => Raaz.Core.Types.Pointer.LengthUnit (Raaz.Core.Primitives.BLOCKS p)


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

-- | Never ending stream of bytes. The reads to the stream might get
--   delayed but it will always return the number of bytes that were asked
--   for.
class InfiniteSource src
slurpBytes :: InfiniteSource src => BYTES Int -> src -> Pointer -> IO src

-- | Abstract byte sources. A bytesource is something that you can use to
--   fill a buffer.
class ByteSource src where fillBytes sz src pointer = Remaining <$> slurp sz src pointer

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

-- | Fills a buffer from the source.
fillBytes :: (ByteSource src, InfiniteSource 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

-- | the buffer is filled completely
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)

-- | A version of slurp that takes type safe lengths as input.
slurp :: (LengthUnit len, InfiniteSource src) => len -> src -> Pointer -> IO 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.Base.Functor Raaz.Core.ByteSource.FillResult
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.Base.Maybe src)
instance Raaz.Core.ByteSource.ByteSource src => Raaz.Core.ByteSource.ByteSource [src]
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.Base.Maybe src)

module Raaz.Core.Random

-- | The class that captures pseudo-random generators. Essentially the a
--   pseudo-random generator (PRG) is a byte sources that can be seeded.
class InfiniteSource prg => PRG prg where type Seed prg :: * where {
    type family Seed prg :: *;
}

-- | Creates a new pseudo-random generators
newPRG :: PRG prg => Seed prg -> IO prg

-- | Re-seeding the prg.
reseed :: PRG prg => Seed prg -> prg -> IO ()

-- | Stuff that can be generated by a pseudo-random generator.
class Random r where random = go undefined where go :: (PRG prg, Storable a) => a -> prg -> IO a go w prg = let sz = byteSize w in allocaBuffer sz $ \ ptr -> do { void $ slurpBytes sz prg ptr; peek $ castPtr ptr }
random :: (Random r, PRG prg) => prg -> IO r
random :: (Random r, PRG prg, Storable r) => prg -> IO r

-- | The system wide pseudo-random generator. The source is expected to be
--   of high quality, albeit a bit slow due to system call overheads. It is
--   expected that this source is automatically seeded from the entropy
--   pool maintained by the platform. Hence, it is neither necessary nor
--   possible to seed this generator which reflected by the fact that the
--   associated type <tt><a>Seed</a> <a>SystemPRG</a></tt> is the unit type
--   <tt>()</tt>.
data SystemPRG
instance Raaz.Core.Random.Random GHC.Types.Word
instance Raaz.Core.Random.Random GHC.Word.Word16
instance Raaz.Core.Random.Random GHC.Word.Word32
instance Raaz.Core.Random.Random GHC.Word.Word64
instance Raaz.Core.Random.Random w => Raaz.Core.Random.Random (Raaz.Core.Types.Endian.LE w)
instance Raaz.Core.Random.Random w => Raaz.Core.Random.Random (Raaz.Core.Types.Endian.BE w)
instance (Raaz.Core.Random.Random a, Raaz.Core.Random.Random b) => Raaz.Core.Random.Random (a, b)
instance (Raaz.Core.Random.Random a, Raaz.Core.Random.Random b, Raaz.Core.Random.Random c) => Raaz.Core.Random.Random (a, b, c)
instance Raaz.Core.ByteSource.InfiniteSource Raaz.Core.Random.SystemPRG
instance Raaz.Core.Random.PRG Raaz.Core.Random.SystemPRG


-- | 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 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 ()) -> 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 ()

-- | 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)

-- | 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 Raaz.Core.Types.Describe.Describable (Raaz.Hash.Internal.HashI h m)
instance Raaz.Core.Types.Describe.Describable (Raaz.Hash.Internal.SomeHashI 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


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

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


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

-- | <i>Deprecated: sha1 and its hmac is mostly broken. Avoid if
--   possible</i>
module Raaz.Hash.Sha1

-- | The cryptographic hash SHA1.

-- | <i>Deprecated: SHA1 is almost broken, avoid it in modern
--   applications.</i>
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)


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

-- | The portable C implementation of SHA256.
implementation :: Implementation SHA256
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


-- | 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 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)


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

-- | The portable C implementation of SHA512.
implementation :: Implementation SHA512
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


-- | 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 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 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 hash of file.
hmacFile :: (Hash h, Recommendation h) => Key (HMAC h) -> FilePath -> IO (HMAC h)

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


-- | 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 (Symmetric cipher, Implementation cipher ~ SomeCipherI 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 ()) -> 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 ()

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

-- | 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.CipherI cipher encMem decMem)
instance Raaz.Core.Types.Describe.Describable (Raaz.Cipher.Internal.SomeCipherI cipher)

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.M128
instance Raaz.Core.Memory.Initialisable Raaz.Cipher.AES.CBC.Implementation.CPortable.M128 (Raaz.Cipher.AES.Internal.KEY128, 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.M256
instance Raaz.Core.Memory.Initialisable Raaz.Cipher.AES.CBC.Implementation.CPortable.M256 (Raaz.Cipher.AES.Internal.KEY256, Raaz.Cipher.AES.Internal.IV)

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

-- | 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
