bearssl: use rand helpers (#113)
This commit is contained in:
parent
47b486b52f
commit
fc6538fa85
|
@ -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))
|
||||
|
||||
|
|
Loading…
Reference in New Issue