Docs · Standard library

@crypto

@crypto holds one function, randomBytes, which fills memory with random bytes from the host. It exists on WebAssembly only.

Vyi
import { randomBytes } from "@crypto"

Exports

NameKindTargetsSummary
randomBytesfunctionwasmfills 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 run gives the same bytes on every run. Its built-in runtime answers random_get from a fixed sequence, so a program run with vyi run sees the same values each time it starts. Do not use those bytes for keys, tokens, or anything that must not be guessed.
  • randomBytes allocates nothing and returns no error value: test the bool.
  • An empty buf returns true and fills nothing.
Vyi
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.