packages feed

crypton-2.3.1 / Crypto / Random / Types.hs

-- |-- Module      : Crypto.Random.Types-- License     : BSD-style-- Maintainer  : Vincent Hanquez <vincent@snarc.org>-- Stability   : experimental-- Portability : Goodmodule Crypto.Random.Types (    MonadRandom (..),    MonadPseudoRandom,    DRG (..),    withDRG,) whereimport Crypto.Internal.ByteArrayimport Crypto.Random.Entropyimport Crypto.Random.SysDRG (sysDRGBytes)-- | A monad constraint that allows to generate random bytes---- Everything in this library that draws a key, a nonce or a signature's-- randomness draws it through this class, and cannot tell a strong source-- from a weak one.  The two instances below are the ones to reach for:-- @IO@ reads the system entropy source, and @MonadPseudoRandom@ runs a-- 'DRG' seeded from it.---- An instance of your own is held to the same standard.  A generator that-- another party can predict, or that repeats, yields keys and signatures-- that give away what they are meant to keep -- so the deliberately-- repeatable instance that makes a test reproducible is not one to ship-- with.class Monad m => MonadRandom m where    getRandomBytes :: ByteArray byteArray => Int -> m byteArray-- | A Deterministic Random Generator (DRG) classclass DRG gen where    -- | Generate N bytes of randomness from a DRG    randomBytesGenerate :: ByteArray byteArray => Int -> gen -> (byteArray, gen)-- | Through the generator of 'Crypto.Random.SysDRG': a ChaCha20 generator-- per operating system thread, reseeded from the system.  Where that-- cannot be seeded -- a system with no @getrandom(2)@ or @getentropy(3)@,-- which includes Windows for now -- this is the system entropy source-- directly, as it was before the generator existed.instance MonadRandom IO where    getRandomBytes n = sysDRGBytes n >>= maybe (getEntropy n) return-- | A simple Monad class very similar to a State Monad-- with the state being a DRG.newtype MonadPseudoRandom gen a = MonadPseudoRandom    { runPseudoRandom :: gen -> (a, gen)    }instance DRG gen => Functor (MonadPseudoRandom gen) where    fmap f m = MonadPseudoRandom $ \g1 ->        let (a, g2) = runPseudoRandom m g1 in (f a, g2)instance DRG gen => Applicative (MonadPseudoRandom gen) where    pure a = MonadPseudoRandom $ \g -> (a, g)    (<*>) fm m = MonadPseudoRandom $ \g1 ->        let (f, g2) = runPseudoRandom fm g1            (a, g3) = runPseudoRandom m g2         in (f a, g3)instance DRG gen => Monad (MonadPseudoRandom gen) where    return = pure    (>>=) m1 m2 = MonadPseudoRandom $ \g1 ->        let (a, g2) = runPseudoRandom m1 g1         in runPseudoRandom (m2 a) g2instance DRG gen => MonadRandom (MonadPseudoRandom gen) where    getRandomBytes n = MonadPseudoRandom (randomBytesGenerate n)-- | Run a pure computation with a Deterministic Random Generator-- in the t'MonadPseudoRandom'withDRG :: DRG gen => gen -> MonadPseudoRandom gen a -> (a, gen)withDRG gen m = runPseudoRandom m gen