From ac77a20c067a63e3b03488abbc0caaf35495cbcc Mon Sep 17 00:00:00 2001 From: Vincent Hanquez Date: Fri, 3 Apr 2015 07:27:44 +0100 Subject: [PATCH] add simple ChaChaRNG --- Crypto/Random/ChaChaDRG.hs | 44 ++++++++++++++++++++++++++++++++++++++ cryptonite.cabal | 1 + 2 files changed, 45 insertions(+) create mode 100644 Crypto/Random/ChaChaDRG.hs diff --git a/Crypto/Random/ChaChaDRG.hs b/Crypto/Random/ChaChaDRG.hs new file mode 100644 index 0000000..0d1999c --- /dev/null +++ b/Crypto/Random/ChaChaDRG.hs @@ -0,0 +1,44 @@ +-- | +-- Module : Crypto.Random.ChaChaDRG +-- License : BSD-style +-- Maintainer : Vincent Hanquez +-- Stability : stable +-- Portability : good +-- +module Crypto.Random.ChaChaDRG + ( ChaChaDRG + , initialize + , initializeWords + ) where + +import Crypto.Random.Types +import Crypto.Internal.ByteArray +import Data.SecureMem +import Data.Word +import Foreign.Storable (pokeElemOff) + +import qualified Crypto.Cipher.ChaCha as C + +instance DRG ChaChaDRG where + randomBytesGenerate = generate + +-- | ChaCha Deterministic Random Generator +newtype ChaChaDRG = ChaChaDRG C.StateSimple + +-- | Initialize a new ChaCha context with the number of rounds, +-- the key and the nonce associated. +initialize :: ByteArray seed + => seed -- ^ 40 bytes of seed + -> ChaChaDRG -- ^ the initial ChaCha state +initialize seed = ChaChaDRG $ C.initializeSimple seed + +-- | Initialize a new ChaCha context from 5-tuple of words64. +-- This interface is useful when creating a RNG out of tests generators (e.g. QuickCheck). +initializeWords :: (Word64, Word64, Word64, Word64, Word64) -> ChaChaDRG +initializeWords (a,b,c,d,e) = initialize (byteArrayAllocAndFreeze 40 fill :: SecureMem) + where fill s = mapM_ (uncurry (pokeElemOff s)) [(0,a), (1,b), (2,c), (3,d), (4,e)] + +generate :: ByteArray byteArray => Int -> ChaChaDRG -> (byteArray, ChaChaDRG) +generate nbBytes st@(ChaChaDRG prevSt) + | nbBytes <= 0 = (empty, st) + | otherwise = let (output, newSt) = C.generateSimple prevSt nbBytes in (output, ChaChaDRG newSt) diff --git a/cryptonite.cabal b/cryptonite.cabal index 0b714d0..72bff6a 100644 --- a/cryptonite.cabal +++ b/cryptonite.cabal @@ -84,6 +84,7 @@ Library Crypto.Hash.Internal.Whirlpool Crypto.Random.Entropy.Source Crypto.Random.Entropy.Backend + Crypto.Random.ChaChaDRG Crypto.Internal.Compat Crypto.Internal.Bytes Crypto.Internal.ByteArray