diff options
| author | Yawning Angel <yawning@schwanenlied.me> | 2021-11-11 07:59:45 +0000 |
|---|---|---|
| committer | Yawning Angel <yawning@schwanenlied.me> | 2021-11-17 14:00:00 +0000 |
| commit | 6bafa21bee56ccfbdf74f88bf7937a900a7d22d9 (patch) | |
| tree | 382a1c9a2f4811bebdd953180684ee6e05827c64 /tests | |
| parent | 61c581baeb94ac73cbb25e93af2710d12e15f25c (diff) | |
crypto: Add rand_bytes
This adds `rand_bytes(dst: []byte)` which fills the destination buffer
with entropy from the cryptographic random number generator. This takes
the "simple is best" approach and just directly returns the OS CSPRNG
output instead of doing anything fancy (a la OpenBSD's arc4random).
Diffstat (limited to 'tests')
| -rw-r--r-- | tests/core/crypto/test_core_crypto.odin | 1 | ||||
| -rw-r--r-- | tests/core/crypto/test_core_crypto_modern.odin | 40 |
2 files changed, 41 insertions, 0 deletions
diff --git a/tests/core/crypto/test_core_crypto.odin b/tests/core/crypto/test_core_crypto.odin index 731833096..2ad00be66 100644 --- a/tests/core/crypto/test_core_crypto.odin +++ b/tests/core/crypto/test_core_crypto.odin @@ -120,6 +120,7 @@ main :: proc() { test_poly1305(&t) test_chacha20poly1305(&t) test_x25519(&t) + test_rand_bytes(&t) bench_modern(&t) diff --git a/tests/core/crypto/test_core_crypto_modern.odin b/tests/core/crypto/test_core_crypto_modern.odin index b3d9e47fd..71adad137 100644 --- a/tests/core/crypto/test_core_crypto_modern.odin +++ b/tests/core/crypto/test_core_crypto_modern.odin @@ -4,6 +4,7 @@ import "core:testing" import "core:fmt" import "core:mem" import "core:time" +import "core:crypto" import "core:crypto/chacha20" import "core:crypto/chacha20poly1305" @@ -304,6 +305,45 @@ test_x25519 :: proc(t: ^testing.T) { } @(test) +test_rand_bytes :: proc(t: ^testing.T) { + log(t, "Testing rand_bytes") + + if ODIN_OS != "linux" { + log(t, "rand_bytes not supported - skipping") + return + } + + allocator := context.allocator + + buf := make([]byte, 1 << 25, allocator) + defer delete(buf) + + // Testing a CSPRNG for correctness is incredibly involved and + // beyond the scope of an implementation that offloads + // responsibility for correctness to the OS. + // + // Just attempt to randomize a sufficiently large buffer, where + // sufficiently large is: + // * Larger than the maximum getentropy request size (256 bytes). + // * Larger than the maximum getrandom request size (2^25 - 1 bytes). + // + // While theoretically non-deterministic, if this fails, chances + // are the CSPRNG is busted. + seems_ok := false + for i := 0; i < 256; i = i + 1 { + mem.zero_explicit(raw_data(buf), len(buf)) + crypto.rand_bytes(buf) + + if buf[0] != 0 && buf[len(buf)-1] != 0 { + seems_ok = true + break + } + } + + expect(t, seems_ok, "Expected to randomize the head and tail of the buffer within a handful of attempts") +} + +@(test) bench_modern :: proc(t: ^testing.T) { fmt.println("Starting benchmarks:") |