diff --git a/websock/utils.nim b/websock/utils.nim index 25772a3..24edf1e 100644 --- a/websock/utils.nim +++ b/websock/utils.nim @@ -7,35 +7,25 @@ ## This file may not be copied, modified, or distributed except according to ## those terms. -import bearssl -export bearssl +import bearssl/[hash, rand] +export rand -## Random helpers: similar as in stdlib, but with BrHmacDrbgContext rng +## Random helpers: similar as in stdlib, but with HmacDrbgContext rng const randMax = 18_446_744_073_709_551_615'u64 type - Rng* = ref BrHmacDrbgContext + Rng* = ref HmacDrbgContext proc newRng*(): Rng = # You should only create one instance of the RNG per application / library # Ref is used so that it can be shared between components - # TODO consider moving to bearssl - var seeder = brPrngSeederSystem(nil) - if seeder == nil: - return nil - - var rng = Rng() - brHmacDrbgInit(addr rng[], addr sha256Vtable, nil, 0) - if seeder(addr rng.vtable) == 0: - return nil - - rng + HmacDrbgContext.new() proc rand*(rng: Rng, max: Natural): int = if max == 0: return 0 var x: uint64 while true: - brHmacDrbgGenerate(addr rng[], addr x, csize_t(sizeof(x))) + let x = rng[].generate(uint64) if x < randMax - (randMax mod (uint64(max) + 1'u64)): # against modulo bias return int(x mod (uint64(max) + 1'u64))