silk.system.random_native.
The native provider of the Random effect: secure random bytes from the operating system.
When to use#
Provide OsRandom for Random in a native program, for keys, nonces, and other secrets. 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, and arc4random_buf on macOS. 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.
OsRandom.makefails to compile on targets other than WASI, Darwin on aarch64, and Linux with GNU libc 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)
// 32 zero bytes from a secure source are practically impossible.
let mut index: usize = 0
while index < 32 {
if key[index] != 0 {
return 0
}
index = index + 1
}
return 1
}Import as OsRandom with import silk.system.random_native { OsRandom }.
Public declarations: 1.
OsRandom#
pub struct OsRandomThe native Random provider: secure random bytes from the operating system. It has no state.
Details#
Each fill gets bytes from random_get on WASI, getrandom on Linux, and arc4random_buf on macOS. 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.