Docs · Standard library
@crypto
@crypto holds one function, randomBytes, which fills memory with random
bytes from the host. It exists on WebAssembly only.
import { randomBytes } from "@crypto"Exports
| Name | Kind | Targets | Summary |
|---|---|---|---|
randomBytes | function | wasm | fills a byte view with random bytes from the host |
On x86-64-linux and arm64-linux, @crypto exports nothing, and a program
that calls randomBytes does not build for those targets.
randomBytes
fn randomBytes(buf: [*mut]u8) bool fills all buf.len bytes of buf and
returns true, or returns false when the host reports a failure.
- The bytes come from the host through WASI's
random_get, so their quality is the host's. A WASI runtime that draws from the operating system's random source gives bytes fit for keys and tokens. vyi rungives the same bytes on every run. Its built-in runtime answersrandom_getfrom a fixed sequence, so a program run withvyi runsees the same values each time it starts. Do not use those bytes for keys, tokens, or anything that must not be guessed.randomBytesallocates nothing and returns no error value: test thebool.- An empty
bufreturnstrueand fills nothing.
import { print, println } from "@fmt"
import { randomBytes } from "@crypto"
fn main() !u8 {
mut token = [8]u8[]
if !randomBytes([*mut]u8(&token)) {
println("no random source")
return Ok(1)
}
for b in token {
print(b)
print(" ")
}
println("")
return Ok(0)
}This prints eight numbers from 0 to 255.
See also: Platform packages for the WASI function behind it, and the targets reference.