Skip to content

Commit

Permalink
WASI: implement in terms of getentropy
Browse files Browse the repository at this point in the history
This isn't really WASI-specific; it should work for any platform that has
`getentropy`.
  • Loading branch information
amesgen committed Aug 13, 2024
1 parent 98dd0cf commit f771c80
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 2 deletions.
2 changes: 2 additions & 0 deletions System/Entropy.hs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ module System.Entropy
import System.EntropyGhcjs
#elif defined(isWindows)
import System.EntropyWindows
#elif wasi_HOST_OS
import System.EntropyWasi
#else
import System.EntropyNix
#endif
Expand Down
39 changes: 39 additions & 0 deletions System/EntropyWasi.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{-# LANGUAGE CApiFFI #-}

module System.EntropyWasi where

import Control.Monad (when)
import Data.ByteString (ByteString)
import Data.ByteString.Internal as B
import Data.Word (Word8)
import Foreign.C.Types
import Foreign.Ptr

data CryptHandle = BogusCryptHandle

openHandle :: IO CryptHandle
openHandle = pure BogusCryptHandle

hGetEntropy :: CryptHandle -> Int -> IO ByteString
hGetEntropy BogusCryptHandle = \n -> B.create n $ go (fromIntegral n)
where
go :: CSize -> Ptr Word8 -> IO ()
go n ptr
| n <= 256 = getentropy' ptr n
| otherwise = do
getentropy' ptr 256
go (n - 256) (ptr `plusPtr` 256)

getentropy' ptr n = do
res <- getentropy ptr n
when (res /= 0) $
fail "getentropy failed"

foreign import capi safe "unistd.h getentropy"
getentropy :: Ptr Word8 -> CSize -> IO CInt

closeHandle :: CryptHandle -> IO ()
closeHandle BogusCryptHandle = pure ()

hardwareRandom :: Int -> IO (Maybe ByteString)
hardwareRandom _ = pure Nothing
7 changes: 5 additions & 2 deletions entropy.cabal
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
cabal-version: >=1.10
cabal-version: 3.8
name: entropy
version: 0.4.1.10
x-revision: 2
Expand All @@ -7,7 +7,7 @@ description: A mostly platform independent method to obtain cryptographically
Users looking for cryptographically strong (number-theoretically
sound) PRNGs should see the 'DRBG' package too.
synopsis: A platform independent entropy source
license: BSD3
license: BSD-3-Clause
license-file: LICENSE
copyright: Thomas DuBuisson <[email protected]>
author: Thomas DuBuisson <[email protected]>
Expand Down Expand Up @@ -61,6 +61,8 @@ library
else {
if os(windows)
other-modules: System.EntropyWindows
elif os(wasi)
other-modules: System.EntropyWasi
else {
other-modules: System.EntropyNix
}
Expand Down Expand Up @@ -90,6 +92,7 @@ library
cpp-options: -DisWindows
cc-options: -DisWindows
extra-libraries: advapi32
elif os(wasi)
else
Build-Depends: unix
c-sources: cbits/getrandom.c cbits/random_initialized.c
Expand Down

0 comments on commit f771c80

Please sign in to comment.