File: RDRand.hs

package info (click to toggle)
haskell-crypton 1.0.4-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 3,548 kB
  • sloc: haskell: 26,764; ansic: 22,294; makefile: 6
file content (39 lines) | stat: -rw-r--r-- 1,067 bytes parent folder | download
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
39
{-# LANGUAGE ForeignFunctionInterface #-}

-- |
-- Module      : Crypto.Random.Entropy.RDRand
-- License     : BSD-style
-- Maintainer  : Vincent Hanquez <vincent@snarc.org>
-- Stability   : experimental
-- Portability : Good
module Crypto.Random.Entropy.RDRand (
    RDRand,
) where

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

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

foreign import ccall unsafe "crypton_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)