API Reference › Crypto › Crypto.random_bytes
method

Crypto.random_bytes

Crypto.random_bytes(n) -> string

Draws n bytes from the operating system's cryptographically-secure random number generator and returns them as a 2n-character lowercase hex string. Use it for unguessable tokens, nonces, and session secrets — anything whose whole value is that an attacker cannot predict it. The result is hex rather than raw bytes for the same reason digests are: a str is null-terminated and raw random bytes can contain a zero byte, so hex is the form you can safely store and compare.

This is deliberately **non-deterministic** — it must never seed the lockstep simulation RNG (Random). Two calls return different values. On a platform without an OS CSPRNG (for example a bare wasm target) the draw degrades to zeroes rather than faulting; treat a real CSPRNG there as a platform-layer responsibility.

Parameters

nthe number of secure random bytes to draw

Example

program Token {
  entry {
    let session = Crypto.random_bytes(16)   # 32 hex chars, unguessable
    print(len(session))                      # 32
  }
}
← All symbols