2020-02-03 07:00:36 +03:00
|
|
|
// Copyright (c) 2019-2020 Alexander Medvednikov. All rights reserved.
|
2019-07-31 04:24:12 +03:00
|
|
|
// Use of this source code is governed by an MIT license
|
|
|
|
// that can be found in the LICENSE file.
|
|
|
|
import crypto.rand
|
|
|
|
|
2020-06-01 07:48:51 +03:00
|
|
|
fn get_random_bytes(no_bytes int) []byte {
|
|
|
|
r := rand.read(no_bytes) or {
|
2019-09-03 16:10:26 +03:00
|
|
|
assert false
|
2020-06-01 07:48:51 +03:00
|
|
|
return []
|
2019-09-03 16:10:26 +03:00
|
|
|
}
|
2020-06-01 07:48:51 +03:00
|
|
|
assert r.len == no_bytes
|
|
|
|
return r
|
|
|
|
}
|
2020-04-26 07:39:23 +03:00
|
|
|
|
2020-06-01 07:48:51 +03:00
|
|
|
fn test_crypto_rand_read() {
|
|
|
|
no_bytes := 100
|
|
|
|
r1 := get_random_bytes(no_bytes)
|
|
|
|
r2 := get_random_bytes(no_bytes)
|
|
|
|
mut equals := 0
|
|
|
|
for i in 0 .. r1.len {
|
|
|
|
if r1[i] == r2[i] {
|
|
|
|
equals++
|
|
|
|
}
|
2019-09-03 16:10:26 +03:00
|
|
|
}
|
2020-06-01 07:48:51 +03:00
|
|
|
assert (100.0 * f32(equals) / f32(no_bytes)) < 20.0
|
2019-07-31 04:24:12 +03:00
|
|
|
}
|
2019-09-17 22:03:54 +03:00
|
|
|
|
2019-09-18 16:12:16 +03:00
|
|
|
fn test_crypto_rand_int_u64() {
|
2019-09-19 13:12:40 +03:00
|
|
|
max := u64(160)
|
2020-06-01 07:48:51 +03:00
|
|
|
mut unique := []u64{}
|
|
|
|
for _ in 0 .. 80 {
|
2019-09-19 13:12:40 +03:00
|
|
|
r := rand.int_u64(max) or {
|
|
|
|
assert false
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if r >= max {
|
|
|
|
assert false
|
|
|
|
}
|
2020-06-01 07:48:51 +03:00
|
|
|
if r !in unique {
|
|
|
|
unique << r
|
2019-09-19 13:12:40 +03:00
|
|
|
}
|
2019-09-17 22:03:54 +03:00
|
|
|
}
|
2020-06-01 07:48:51 +03:00
|
|
|
assert unique.len >= 10
|
2019-09-17 22:03:54 +03:00
|
|
|
}
|