cprng-aes-0.5.2/0000755000000000000000000000000012213007235011556 5ustar0000000000000000cprng-aes-0.5.2/LICENSE0000644000000000000000000000273112213007235012566 0ustar0000000000000000Copyright (c) 2010-2011 Vincent Hanquez All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the author nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. cprng-aes-0.5.2/README.md0000644000000000000000000000207312213007235013037 0ustar0000000000000000CPRNG-AES ========= This module provides a crypto pseudo random number generator using AES in counter mode. to import: import Crypto.Random.AESCtr to use: rng <- makeSystem let (ran, rng') = getRandomBytes rng 1024 it's also an instance of CryptoRandomGen from the crypto-api package. Statistics ---------- Using ent, a randomness property maker on one 1Mb sample. cprng-AES: Entropy = 7.999837 bits per byte. Optimum compression would reduce the size of this 1048576 byte file by 0 percent. Chi square distribution for 1048576 samples is 237.02. Arithmetic mean value of data bytes is 127.3422 (127.5 = random). Monte Carlo value for Pi is 3.143589568 (error 0.06 percent). Compared to urandom with the same sampling: Entropy = 7.999831 bits per byte. Optimum compression would reduce the size of this 1048576 byte file by 0 percent. Chi square distribution for 1048576 samples is 246.63. Arithmetic mean value of data bytes is 127.6347 (127.5 = random). Monte Carlo value for Pi is 3.132465868 (error 0.29 percent). cprng-aes-0.5.2/Setup.hs0000644000000000000000000000005612213007235013213 0ustar0000000000000000import Distribution.Simple main = defaultMain cprng-aes-0.5.2/cprng-aes.cabal0000644000000000000000000000431612213007235014425 0ustar0000000000000000Name: cprng-aes Version: 0.5.2 Description: Simple crypto pseudo-random-number-generator with really good randomness property. . Using ent, a randomness property maker on one 1Mb sample: Entropy = 7.999837 bits per byte. Optimum compression would reduce the size of this 1048576 byte file by 0 percent. Chi square distribution for 1048576 samples is 237.02 Arithmetic mean value of data bytes is 127.3422 (127.5 = random) Monte Carlo value for Pi is 3.143589568 (error 0.06 percent) . Compared to urandom with the same sampling: Entropy = 7.999831 bits per byte. Optimum compression would reduce the size of this 1048576 byte file by 0 percent. Chi square distribution for 1048576 samples is 246.63 Arithmetic mean value of data bytes is 127.6347 (127.5 = random). Monte Carlo value for Pi is 3.132465868 (error 0.29 percent). License: BSD3 License-file: LICENSE Copyright: Vincent Hanquez Author: Vincent Hanquez Maintainer: Vincent Hanquez Synopsis: Crypto Pseudo Random Number Generator using AES in counter mode. Build-Type: Simple Category: Cryptography stability: experimental Cabal-Version: >=1.8 Homepage: http://github.com/vincenthz/hs-cprng-aes data-files: README.md Library Build-Depends: base >= 3 && < 5 , bytestring , byteable , random , crypto-random >= 0.0.7 && < 0.1 Exposed-modules: Crypto.Random.AESCtr Other-modules: Crypto.Random.AESCtr.Internal ghc-options: -Wall Build-Depends: cipher-aes >= 0.2 && < 0.3 Benchmark bench-cprng-aes hs-source-dirs: Benchmarks Main-Is: Benchmarks.hs type: exitcode-stdio-1.0 Build-depends: base >= 4 && < 5 , bytestring , crypto-random , cprng-aes , criterion , mtl source-repository head type: git location: git://github.com/vincenthz/hs-cprng-aes cprng-aes-0.5.2/Benchmarks/0000755000000000000000000000000012213007235013633 5ustar0000000000000000cprng-aes-0.5.2/Benchmarks/Benchmarks.hs0000644000000000000000000000220612213007235016244 0ustar0000000000000000module Main where import Criterion.Main import qualified Data.ByteString as B import Crypto.Random.AESCtr import Crypto.Random import System.IO.Unsafe (unsafePerformIO) import Data.IORef gen rng n = fst (cprgGenerate n rng) gen2 rngref n = unsafePerformIO $ do rng <- readIORef rngref let (b, rng2) = cprgGenerate n rng writeIORef rngref rng2 return b main = do rng <- makeSystem rngref <- newIORef rng defaultMain [ bgroup "generate random bytes (init)" [ bench "1" $ nf (gen rng) 1 , bench "8" $ nf (gen rng) 8 , bench "16" $ nf (gen rng) 16 , bench "256" $ nf (gen rng) 256 , bench "1024" $ nf (gen rng) 1024 , bench "4096" $ nf (gen rng) 4096 ] , bgroup "generate random bytes (continous)" [ bench "1" $ nf (gen2 rngref) 1 , bench "8" $ nf (gen2 rngref) 8 , bench "16" $ nf (gen2 rngref) 16 , bench "256" $ nf (gen2 rngref) 256 , bench "1024" $ nf (gen2 rngref) 1024 , bench "4096" $ nf (gen2 rngref) 4096 ] ] cprng-aes-0.5.2/Crypto/0000755000000000000000000000000012213007235013036 5ustar0000000000000000cprng-aes-0.5.2/Crypto/Random/0000755000000000000000000000000012213007235014256 5ustar0000000000000000cprng-aes-0.5.2/Crypto/Random/AESCtr.hs0000644000000000000000000001153312213007235015676 0ustar0000000000000000-- | -- Module : Crypto.Random.AESCtr -- License : BSD-style -- Maintainer : Vincent Hanquez -- Stability : stable -- Portability : unknown -- -- this CPRNG is an AES based counter system. -- -- the internal size of fields are: 16 bytes IV, 16 bytes counter, 32 bytes key -- -- each block are generated the following way: -- aes (IV `xor` counter) -> 16 bytes output -- {-# LANGUAGE CPP #-} {-# LANGUAGE BangPatterns #-} module Crypto.Random.AESCtr ( AESRNG , make , makeSystem ) where import Crypto.Random import System.Random (RandomGen(..)) import Crypto.Random.AESCtr.Internal import Control.Arrow (second) import Data.ByteString (ByteString) import qualified Data.ByteString as B import Data.Byteable import Data.Bits (xor, (.&.)) -- | AES Counter mode Pseudo random generator. -- -- Provide a very good Cryptographic pseudo random generator -- that create pseudo random output based an AES cipher -- used in counter mode, initialized from random key, random IV -- and random nonce. -- -- This CPRG uses 64 bytes of pure entropy to create its random state. -- -- By default, this generator will automatically reseed after generating -- 1 megabyte of data. data AESRNG = AESRNG { aesrngState :: RNG , aesrngEntropy :: EntropyPool , aesrngThreshold :: Int -- ^ in number of generated block , aesrngCache :: ByteString } instance Show AESRNG where show _ = "aesrng[..]" makeFrom :: EntropyPool -> B.ByteString -> AESRNG makeFrom entPool b = AESRNG { aesrngState = rng , aesrngEntropy = entPool , aesrngThreshold = 1024 -- in blocks generated, so 1mb , aesrngCache = B.empty } where rng = RNG (get128 iv) (get128 cnt) 0 key (key, cnt, iv) = makeParams b -- | make an AES RNG from an EntropyPool. -- -- use `makeSystem` to not have to deal with the entropy pool. make :: EntropyPool -> AESRNG make entPool = makeFrom entPool b where !b = toBytes $ grabEntropy 64 entPool -- | Initialize a new AES RNG using the system entropy. -- {-# DEPRECATED makeSystem "use cprgCreate with an entropy pool" #-} makeSystem :: IO AESRNG makeSystem = make `fmap` createEntropyPool -- | get a Random number of bytes from the RNG. -- it generate randomness by block of chunkSize bytes and will returns -- a block bigger or equal to the size requested. genRandomBytesState :: RNG -> Int -> (ByteString, RNG) genRandomBytesState rng n | n <= chunkSize = genNextChunk rng | otherwise = let (bs, rng') = acc 0 [] rng in (B.concat bs, rng') where acc l bs g | l * chunkSize >= n = (bs, g) | otherwise = let (b, g') = genNextChunk g in acc (l+1) (b:bs) g' genRanBytesNoCheck :: AESRNG -> Int -> (ByteString, AESRNG) genRanBytesNoCheck rng n | B.length (aesrngCache rng) >= n = let (b1,b2) = B.splitAt n (aesrngCache rng) in (b1, rng { aesrngCache = b2 }) | otherwise = let (b, rng') = genRandomBytesState (aesrngState rng) n (b1, b2) = B.splitAt n b in (b1, rng { aesrngState = rng', aesrngCache = b2 }) -- | generate a random set of bytes genRanBytes :: AESRNG -> Int -> (ByteString, AESRNG) genRanBytes rng n = second reseedThreshold $ genRanBytesNoCheck rng n reseedThreshold :: AESRNG -> AESRNG reseedThreshold rng | getNbChunksGenerated (aesrngState rng) >= lvl = let ent = toBytes $ grabEntropy 64 (aesrngEntropy rng) in rng { aesrngState = reseedState ent (aesrngState rng) } | otherwise = rng where lvl = aesrngThreshold rng reseedState :: ByteString -> RNG -> RNG reseedState b g@(RNG _ cnt1 _ _) = RNG (get128 r16 `xor128` get128 iv2) (cnt1 `xor128` get128 cnt2) 0 key2 where (r16, _) = genNextChunk g (key2, cnt2, iv2) = makeParams b instance CPRG AESRNG where cprgCreate = make cprgSetReseedThreshold lvl rng = reseedThreshold (rng { aesrngThreshold = if nbChunks > 0 then nbChunks else 1 }) where nbChunks = lvl `div` chunkSize cprgGenerate len rng = genRanBytes rng len cprgGenerateWithEntropy len rng = let ent = toBytes $ grabEntropy len (aesrngEntropy rng) (bs, rng') = genRanBytes rng len in (B.pack $ B.zipWith xor ent bs, rng') cprgFork rng = let (b,rng') = genRanBytes rng 64 in (rng', makeFrom (aesrngEntropy rng) b) instance RandomGen AESRNG where next rng = let (bs, rng') = genRanBytes rng 16 in let (Word128 a _) = get128 bs in let n = fromIntegral (a .&. 0x7fffffff) in (n, rng') split rng = let rng' = make (aesrngEntropy rng) in (rng, rng') genRange _ = (0, 0x7fffffff) cprng-aes-0.5.2/Crypto/Random/AESCtr/0000755000000000000000000000000012213007235015337 5ustar0000000000000000cprng-aes-0.5.2/Crypto/Random/AESCtr/Internal.hs0000644000000000000000000000452712213007235017457 0ustar0000000000000000-- | -- Module : Crypto.Random.AESCtr.Internal -- License : BSD-style -- Maintainer : Vincent Hanquez -- Stability : stable -- Portability : unknown -- {-# LANGUAGE CPP #-} module Crypto.Random.AESCtr.Internal where import qualified Crypto.Cipher.AES as AES import Data.ByteString (ByteString) import qualified Data.ByteString as B import Data.Word import Data.Bits (xor) import Foreign.Ptr #if __GLASGOW_HASKELL__ > 704 import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr) #else import Foreign.ForeignPtr (unsafeForeignPtrToPtr) #endif import Foreign.Storable import qualified Data.ByteString.Internal as B data Word128 = Word128 {-# UNPACK #-} !Word64 {-# UNPACK #-} !Word64 {-| An opaque object containing an AES CPRNG -} data RNG = RNG {-# UNPACK #-} !Word128 -- iv {-# UNPACK #-} !Word128 -- cnt {-# UNPACK #-} !Int -- number of chunks generated since reseed {-# UNPACK #-} !AES.AES -- AES context getNbChunksGenerated :: RNG -> Int getNbChunksGenerated (RNG _ _ c _) = c put128 :: Word128 -> ByteString put128 (Word128 a b) = B.unsafeCreate 16 (write64 . castPtr) where write64 :: Ptr Word64 -> IO () write64 ptr = poke ptr a >> poke (ptr `plusPtr` 8) b get128 :: ByteString -> Word128 get128 (B.PS ps s _) = B.inlinePerformIO $ do let ptr = castPtr (unsafeForeignPtrToPtr ps `plusPtr` s) :: Ptr Word64 a <- peek ptr b <- peek (ptr `plusPtr` 8) return $ Word128 a b xor128 :: Word128 -> Word128 -> Word128 xor128 (Word128 a1 b1) (Word128 a2 b2) = Word128 (a1 `xor` a2) (b1 `xor` b2) add64 :: Word128 -> Word128 add64 (Word128 a b) = if nb < 64 then Word128 (a+1) nb else Word128 a nb where nb = b + 64 {- withBsPtr :: ByteString -> (Ptr Word8 -> IO a) -> IO a withBsPtr (B.PS ps s _) f = withForeignPtr ps $ \ptr -> f (ptr `plusPtr` s) -} makeParams :: ByteString -> (AES.AES, ByteString, ByteString) makeParams b = (key, cnt, iv) where key = AES.initAES $ B.take 32 left2 (cnt, left2) = B.splitAt 16 left1 (iv, left1) = B.splitAt 16 b chunkSize :: Int chunkSize = 1024 genNextChunk :: RNG -> (ByteString, RNG) genNextChunk (RNG iv counter nbChunks key) = (chunk, newrng) where newrng = RNG (get128 chunk) (add64 counter) (nbChunks+1) key chunk = AES.genCTR key bytes chunkSize bytes = put128 (iv `xor128` counter)