2021-03-11 03:34:14 +00:00
|
|
|
import bearssl
|
2021-04-13 22:05:58 +00:00
|
|
|
export bearssl
|
2021-03-11 03:34:14 +00:00
|
|
|
|
|
|
|
## Random helpers: similar as in stdlib, but with BrHmacDrbgContext rng
|
|
|
|
const randMax = 18_446_744_073_709_551_615'u64
|
|
|
|
|
2021-05-25 14:02:32 +00:00
|
|
|
type
|
|
|
|
Rng* = ref BrHmacDrbgContext
|
|
|
|
|
2021-06-01 02:39:14 +00:00
|
|
|
proc newRng*(): Rng =
|
2021-04-13 22:05:58 +00:00
|
|
|
# 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
|
|
|
|
|
2021-06-01 02:39:14 +00:00
|
|
|
var rng = Rng()
|
2021-04-13 22:05:58 +00:00
|
|
|
brHmacDrbgInit(addr rng[], addr sha256Vtable, nil, 0)
|
|
|
|
if seeder(addr rng.vtable) == 0:
|
|
|
|
return nil
|
2021-06-01 02:39:14 +00:00
|
|
|
|
2021-04-13 22:05:58 +00:00
|
|
|
rng
|
|
|
|
|
2021-05-25 22:39:10 +00:00
|
|
|
proc rand*(rng: Rng, max: Natural): int =
|
2021-03-11 03:34:14 +00:00
|
|
|
if max == 0: return 0
|
|
|
|
var x: uint64
|
|
|
|
while true:
|
2021-05-25 22:39:10 +00:00
|
|
|
brHmacDrbgGenerate(addr rng[], addr x, csize_t(sizeof(x)))
|
2021-03-11 03:34:14 +00:00
|
|
|
if x < randMax - (randMax mod (uint64(max) + 1'u64)): # against modulo bias
|
|
|
|
return int(x mod (uint64(max) + 1'u64))
|
|
|
|
|
2021-05-25 22:39:10 +00:00
|
|
|
proc genMaskKey*(rng: Rng): array[4, char] =
|
2021-03-11 03:34:14 +00:00
|
|
|
## Generates a random key of 4 random chars.
|
2021-05-25 22:39:10 +00:00
|
|
|
proc r(): char = char(rand(rng, 255))
|
2021-03-11 03:34:14 +00:00
|
|
|
return [r(), r(), r(), r()]
|
|
|
|
|
2021-05-25 22:39:10 +00:00
|
|
|
proc genWebSecKey*(rng: Rng): seq[byte] =
|
2021-03-18 15:30:21 +00:00
|
|
|
var key = newSeq[byte](16)
|
2021-05-25 22:39:10 +00:00
|
|
|
proc r(): byte = byte(rand(rng, 255))
|
2021-03-11 03:34:14 +00:00
|
|
|
## Generates a random key of 16 random chars.
|
|
|
|
for i in 0..15:
|
|
|
|
key.add(r())
|
|
|
|
return key
|