File: EntropyGhcjs.hs

package info (click to toggle)
haskell-entropy 0.4.1.11-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 100 kB
  • sloc: haskell: 358; ansic: 182; makefile: 2
file content (51 lines) | stat: -rw-r--r-- 1,319 bytes parent folder | download | duplicates (3)
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
40
41
42
43
44
45
46
47
48
49
50
51
{-|
 Maintainer: Thomas.DuBuisson@gmail.com
 Stability: beta
 Portability: portable

 Obtain entropy from system sources or x86 RDRAND when available.

-}

module System.EntropyGhcjs
        ( CryptHandle
        , openHandle
        , hGetEntropy
        , closeHandle
        , hardwareRandom
        ) where

import Data.ByteString as B
import GHCJS.DOM.Crypto as Crypto
import GHCJS.DOM.Types (ArrayBufferView (..), fromJSValUnchecked)
import GHCJS.DOM.GlobalCrypto (getCrypto)
import GHCJS.DOM (globalThisUnchecked)
import Language.Javascript.JSaddle.Object as JS


-- |Handle for manual resource management
newtype CryptHandle = CH Crypto

-- | Get random values from the hardware RNG or return Nothing if no
-- supported hardware RNG is available.
--
-- Not supported on ghcjs.
hardwareRandom :: Int -> IO (Maybe B.ByteString)
hardwareRandom _ = pure Nothing

-- |Open a `CryptHandle`
openHandle :: IO CryptHandle
openHandle = do
  this <- globalThisUnchecked
  CH <$> getCrypto this

-- |Close the `CryptHandle`
closeHandle :: CryptHandle -> IO ()
closeHandle _ = pure ()

-- |Read random data from a `CryptHandle`
hGetEntropy :: CryptHandle -> Int -> IO B.ByteString
hGetEntropy (CH h) n = do
  arr <- JS.new (jsg "Int8Array") [n]
  getRandomValues_ h (ArrayBufferView arr)
  B.pack <$> fromJSValUnchecked arr