2021-06-20 11:27:50 +07:00
|
|
|
## nim-ws
|
|
|
|
## Copyright (c) 2021 Status Research & Development GmbH
|
|
|
|
## Licensed under either of
|
|
|
|
## * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
|
|
|
|
## * MIT license ([LICENSE-MIT](LICENSE-MIT))
|
|
|
|
## at your option.
|
|
|
|
## This file may not be copied, modified, or distributed except according to
|
|
|
|
## those terms.
|
|
|
|
|
2021-03-11 09:04:14 +05:30
|
|
|
import bearssl
|
2021-04-14 03:35:58 +05:30
|
|
|
export bearssl
|
2021-03-11 09:04:14 +05:30
|
|
|
|
|
|
|
## Random helpers: similar as in stdlib, but with BrHmacDrbgContext rng
|
|
|
|
const randMax = 18_446_744_073_709_551_615'u64
|
|
|
|
|
2021-05-25 08:02:32 -06:00
|
|
|
type
|
|
|
|
Rng* = ref BrHmacDrbgContext
|
|
|
|
|
2021-05-31 20:39:14 -06:00
|
|
|
proc newRng*(): Rng =
|
2021-04-14 03:35:58 +05:30
|
|
|
# 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-05-31 20:39:14 -06:00
|
|
|
var rng = Rng()
|
2021-04-14 03:35:58 +05:30
|
|
|
brHmacDrbgInit(addr rng[], addr sha256Vtable, nil, 0)
|
|
|
|
if seeder(addr rng.vtable) == 0:
|
|
|
|
return nil
|
2021-05-31 20:39:14 -06:00
|
|
|
|
2021-04-14 03:35:58 +05:30
|
|
|
rng
|
|
|
|
|
2021-05-25 16:39:10 -06:00
|
|
|
proc rand*(rng: Rng, max: Natural): int =
|
2021-03-11 09:04:14 +05:30
|
|
|
if max == 0: return 0
|
|
|
|
var x: uint64
|
|
|
|
while true:
|
2021-05-25 16:39:10 -06:00
|
|
|
brHmacDrbgGenerate(addr rng[], addr x, csize_t(sizeof(x)))
|
2021-03-11 09:04:14 +05:30
|
|
|
if x < randMax - (randMax mod (uint64(max) + 1'u64)): # against modulo bias
|
|
|
|
return int(x mod (uint64(max) + 1'u64))
|
|
|
|
|
2021-05-25 16:39:10 -06:00
|
|
|
proc genMaskKey*(rng: Rng): array[4, char] =
|
2021-03-11 09:04:14 +05:30
|
|
|
## Generates a random key of 4 random chars.
|
2021-05-25 16:39:10 -06:00
|
|
|
proc r(): char = char(rand(rng, 255))
|
2021-03-11 09:04:14 +05:30
|
|
|
return [r(), r(), r(), r()]
|
|
|
|
|
2021-05-25 16:39:10 -06:00
|
|
|
proc genWebSecKey*(rng: Rng): seq[byte] =
|
2021-03-18 09:30:21 -06:00
|
|
|
var key = newSeq[byte](16)
|
2021-05-25 16:39:10 -06:00
|
|
|
proc r(): byte = byte(rand(rng, 255))
|
2021-03-11 09:04:14 +05:30
|
|
|
## Generates a random key of 16 random chars.
|
|
|
|
for i in 0..15:
|
2021-06-12 07:54:38 +07:00
|
|
|
key[i] = r()
|
2021-03-11 09:04:14 +05:30
|
|
|
return key
|