silk.system.random_native.
The system provider of the Random effect: secure random bytes from the operating system or
the JavaScript host.
When to use#
Provide OsRandom for Random in a program, for keys, nonces, and other secrets. The same
provider works on each supported target, a browser included, so the program does not choose a
source by target. In a test, provide a fake that returns fixed bytes.
Details#
Each fill gets bytes from the secure random source of the system: random_get on WASI,
getrandom on Linux, arc4random_buf on macOS, ProcessPrng on Windows, and the host's
silk.random import (crypto.getRandomValues) on wasm32-unknown-unknown. An empty buffer
does nothing.
Gotchas#
A failure of the source is a trap, because weak bytes are not safe. Part of the buffer can be changed before the trap.
On Linux, it needs glibc 2.25 and Linux 3.17 or later.
On
wasm32-unknown-unknown, the host suppliessilk.random. The standard library'shost/wasm-runner.mjsand themountofui-app-domdo.OsRandom.makefails to compile on targets other than a JavaScript host, WASI, Windows on x86_64, Darwin on x86_64 or aarch64, and GNU Linux on x86_64 or aarch64.
Examples#
Make a random key#
import silk.core.effect { Effect }
import silk.system.random_native { OsRandom }
import silk.system.random { Random }
pub fn main() -> i32 {
let mut random = OsRandom.make()
let mut key: [u8; 32] = [0; 32]
run Random.fillBytes(&mut key) |> Effect.provideMut<Random>(&mut random)
// The key can now be passed to the operation that needs it.
return 0
}Import as OsRandom with import silk.system.random_native { OsRandom }.
Public declarations: 1.
OsRandom#
pub struct OsRandomThe system Random provider: secure random bytes from the operating system or the JavaScript
host. It has no state.
Details#
Each fill gets bytes from random_get on WASI, getrandom on Linux, arc4random_buf on macOS,
ProcessPrng on Windows, and the host's silk.random import on wasm32-unknown-unknown. An
empty buffer does nothing.
Gotchas#
A failure of the source is a trap, because weak bytes are not safe. Part of the buffer can be changed before the trap.
On Linux, it needs glibc 2.25 and Linux 3.17 or later.
Implementation OsRandom#
impl OsRandomAssociated function make#
pub fn make() -> OsRandomReturns a provider. It does not read random bytes.
Implementation Random for OsRandom#
impl Random for OsRandomOperation fillBytes#
effect fn fillBytes(self: &mut Self, output: &mut [u8]) -> ()Category: System.
Profiles: aarch64-apple-darwin, aarch64-unknown-linux-gnu, aarch64-unknown-linux-gnu-no-libc, x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-no-libc, wasm32-unknown-unknown, wasm32-wasip1, wasm32-wasip2, x86_64-pc-windows-msvc, wasm64-unknown-unknown.