File: RDRand.hs

package info (click to toggle)
haskell-crypto-random 0.0.9-10
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 96 kB
  • sloc: haskell: 401; ansic: 52; makefile: 2
file content (38 lines) | stat: -rw-r--r-- 1,086 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
-- |
-- Module      : Crypto.Random.Entropy.RDRand
-- License     : BSD-style
-- Maintainer  : Vincent Hanquez <vincent@snarc.org>
-- Stability   : experimental
-- Portability : Good
--
{-# LANGUAGE ForeignFunctionInterface #-}
module Crypto.Random.Entropy.RDRand
    ( RDRand
    ) where

import Foreign.Ptr
import Foreign.C.Types
import Data.Word (Word8)
import Crypto.Random.Entropy.Source

foreign import ccall unsafe "crypto_random_cpu_has_rdrand"
   c_cpu_has_rdrand :: IO CInt

foreign import ccall unsafe "crypto_random_get_rand_bytes"
  c_get_rand_bytes :: Ptr Word8 -> CInt -> IO CInt

-- | fake handle to Intel RDRand entropy cpu instruction
data RDRand = RDRand

instance EntropySource RDRand where
    entropyOpen     = rdrandGrab
    entropyGather _ = rdrandGetBytes
    entropyClose  _ = return ()

rdrandGrab :: IO (Maybe RDRand)
rdrandGrab = supported `fmap` c_cpu_has_rdrand
  where supported 0 = Nothing
        supported _ = Just RDRand

rdrandGetBytes :: Ptr Word8 -> Int -> IO Int
rdrandGetBytes ptr sz = fromIntegral `fmap` c_get_rand_bytes ptr (fromIntegral sz)