{-# LANGUAGE FlexibleInstances, TypeSynonymInstances, CPP #-}{-|
Maintainer: Thomas.DuBuisson@gmail.com
Stability: beta
Portability: portable
This module is for instantiating cryptographically strong
determinitic random bit generators (DRBGs, aka PRNGs) For the simple
use case of using the system random number generator
('System.Crypto.Random') to seed the DRBG:
@ g <- newGenIO
@
Users needing to provide their own entropy can call 'newGen' directly
@ entropy <- getEntropy nrBytes
let generator = newGen entropy
@
-}moduleCrypto.Random(-- * Basic InterfaceCryptoRandomGen(..),GenError(..)-- * Helper functions and expanded interface,splitGen-- * Instances,SystemRandom)whereimportSystem.EntropyimportCrypto.TypesimportControl.Monad(liftM)importqualifiedData.ByteStringasBimportqualifiedData.ByteString.LazyasLimportData.TaggedimportData.Bits(xor,setBit,shiftR,shiftL,(.&.))importData.List(foldl')importSystem.IO.Unsafe(unsafeInterleaveIO)importqualifiedForeign.ForeignPtrasFP#if MIN_VERSION_tagged(0,2,0)importData.Proxy#endif-- |many generators have these error conditions in commondataGenError=GenErrorOtherString-- ^ Misc|RequestedTooManyBytes-- ^ Requested more bytes than a single pass can generate (The maximum request is generator dependent)|RangeInvalid-- ^ When using @genInteger g (l,h)@ and @logBase 2 (h - l) > (maxBound :: Int)@.|NeedReseed-- ^ Some generators cease operation after too high a count without a reseed (ex: NIST SP 800-90)|NotEnoughEntropy-- ^ For instantiating new generators (or reseeding)|NeedsInfiniteSeed-- ^ This generator can not be instantiated or reseeded with a finite seed (ex: 'SystemRandom')deriving(Eq,Ord,Show)-- |A class of random bit generators that allows for the possibility-- of failure, reseeding, providing entropy at the same time as-- requesting bytes---- Minimum complete definition: `newGen`, `genSeedLength`, `genBytes`,-- `reseed`.classCryptoRandomGengwhere-- |Instantiate a new random bit generator. The provided-- bytestring should be of length >= genSeedLength. If the-- bytestring is shorter then the call may fail (suggested-- error: `NotEnoughEntropy`). If the bytestring is of-- sufficent length the call should always succeed.newGen::B.ByteString->EitherGenErrorg-- |Length of input entropy necessary to instantiate or reseed-- a generatorgenSeedLength::TaggedgByteLength-- | @genBytes len g@ generates a random ByteString of length-- @len@ and new generator. The "MonadCryptoRandom" package-- has routines useful for converting the ByteString to-- commonly needed values (but "cereal" or other-- deserialization libraries would also work).---- This routine can fail if the generator has gone too long-- without a reseed (usually this is in the ball-park of 2^48-- requests). Suggested error in this cases is `NeedReseed`genBytes::ByteLength->g->EitherGenError(B.ByteString,g)-- |@genBytesWithEntropy g i entropy@ generates @i@ random-- bytes and use the additional input @entropy@ in the-- generation of the requested data to increase the confidence-- our generated data is a secure random stream.---- Some generators use @entropy@ to perturb the state of the-- generator, meaning:---- @-- (_,g2') <- genBytesWithEntropy len g1 ent-- (_,g2 ) <- genBytes len g1-- g2 /= g2'-- @---- But this is not required.---- Default:-- -- @-- genBytesWithEntropy g bytes entropy = xor entropy (genBytes g bytes)-- @genBytesWithEntropy::ByteLength->B.ByteString->g->EitherGenError(B.ByteString,g)genBytesWithEntropylenentropyg=letres=genByteslengincaseresofLefterr->LefterrRight(bs,g')->letentropy'=B.appendentropy(B.replicate(len-B.lengthentropy)0)inRight(zwp'entropy'bs,g')-- |If the generator has produced too many random bytes on its-- existing seed it will throw `NeedReseed`. In that case,-- reseed the generator using this function and a new-- high-entropy seed of length >= `genSeedLength`. Using-- bytestrings that are too short can result in an error-- (`NotEnoughEntropy`).reseed::B.ByteString->g->EitherGenErrorg-- |By default this uses "System.Crypto.Random" to obtain-- entropy for `newGen`.newGenIO::IOgnewGenIO=go0wherego1000=error"The generator instance requested by newGenIO never instantiates (1000 tries). It must be broken."goi=doletp=ProxygetTypedGen::(CryptoRandomGeng)=>Proxyg->IO(EitherGenErrorg)getTypedGenpr=liftMnewGen(getEntropy$proxygenSeedLengthpr)res<-getTypedGenpcaseresofLeft_->go(i+1)Rightg->return(g`asProxyTypeOf`p)-- |get a random number generator based on the standard system entropy sourcegetSystemGen::IOSystemRandomgetSystemGen=doch<-openHandleletgetBS=unsafeInterleaveIO$dobs<-hGetEntropych((2^15)-16)more<-getBSreturn(bs:more)liftM(SysRandom.L.fromChunks)getBS-- |Not that it is technically correct as an instance of-- 'CryptoRandomGen', but simply because it's a reasonable engineering-- choice here is a CryptoRandomGen which streams the system-- randoms. Take note:-- -- * It uses the default definition of 'genByteWithEntropy'---- * 'newGen' will always fail!---- * 'reseed' will always fail!---- * the handle to the system random is never closed--dataSystemRandom=SysRandomL.ByteStringinstanceCryptoRandomGenSystemRandomwherenewGen_=LeftNeedsInfiniteSeedgenSeedLength=TaggedmaxBoundgenBytesreq(SysRandombs)=letreqI=fromIntegralreqrnd=L.takereqIbsrest=L.dropreqIbsinifL.lengthrnd==reqIthenRight(B.concat$L.toChunksrnd,SysRandomrest)elseLeft$GenErrorOther"Error obtaining enough bytes from system random for given request"reseed__=LeftNeedsInfiniteSeednewGenIO=getSystemGen-- | While the safety and wisdom of a splitting function depends on the-- properties of the generator being split, several arguments from-- informed people indicate such a function is safe for NIST SP 800-90-- generators. (see libraries\@haskell.org discussion around Sept, Oct-- 2010)splitGen::CryptoRandomGeng=>g->EitherGenError(g,g)splitGeng=dolete=genBytes(genSeedLength`for`g)gcaseeofLefte->LefteRight(ent,g')->casenewGenentofRightnew->Right(g',new)Lefte->Lefte-- |Obtain a tagged value for a particular instantiated type.for::Taggedab->a->bfort_=unTaggedt-- |Helper function to convert bytestrings to integersbs2i::B.ByteString->Integerbs2ibs=B.foldl'(\ib->(i`shiftL`8)+fromIntegralb)0bs{-# INLINE bs2i #-}-- |zipWith xor + Pack-- As a result of rewrite rules, this should automatically be optimized (at compile time) -- to use the bytestring libraries 'zipWith'' function.zwp'a=B.pack.B.zipWithxora{-# INLINE zwp' #-}