diff --git a/System/Entropy.hs b/System/Entropy.hs index 9868fe5..50eb301 100644 --- a/System/Entropy.hs +++ b/System/Entropy.hs @@ -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 diff --git a/System/EntropyWasi.hs b/System/EntropyWasi.hs new file mode 100644 index 0000000..667b516 --- /dev/null +++ b/System/EntropyWasi.hs @@ -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 diff --git a/entropy.cabal b/entropy.cabal index 45720f0..f2adf0a 100644 --- a/entropy.cabal +++ b/entropy.cabal @@ -1,4 +1,4 @@ -cabal-version: >=1.10 +cabal-version: 3.8 name: entropy version: 0.4.1.10 x-revision: 2 @@ -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 author: Thomas DuBuisson @@ -17,7 +17,7 @@ homepage: https://github.com/TomMD/entropy bug-reports: https://github.com/TomMD/entropy/issues stability: stable -build-type: Custom +build-type: Simple tested-with: GHC == 9.10.1 @@ -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 } @@ -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