# std/sysrand

Dark Mode

- Manual
- Standard library
- Index
- Compiler docs
- Fusion docs
- devel, stable

Search:
Source Edit

Warning: This module was added in Nim 1.6. If you are using it for cryptographic purposes, keep in mind that so far this has not been audited by any security professionals, therefore may not be secure.

`std/sysrand` generates random numbers from a secure source provided by the operating system. It is a cryptographically secure pseudorandom number generator and should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation.

Targets | Implementation
--- | ---
Windows | BCryptGenRandom
Linux | getrandom
MacOSX | getentropy
iOS | SecRandomCopyBytes
OpenBSD | getentropy openbsd
FreeBSD | getrandom freebsd
JS (Web Browser) | getRandomValues
Node.js | randomFillSync
Other Unix platforms | /dev/urandom

On a Linux target, a call to the `getrandom` syscall can be avoided (e.g. for targets running kernel version < 3.17) by passing a compile flag of `-d:nimNoGetRandom`. If this flag is passed, sysrand will use `/dev/urandom` as with any other POSIX compliant OS.

Example:

    import std/sysrand
    doAssert urandom(0).len == 0
    doAssert urandom(113).len == 113
    doAssert urandom(1234) != urandom(1234) # unlikely to fail in practice

# See also

- random module

# Imports

os

# Procs

    proc urandom(dest: var openArray[byte]): bool {....raises: [], tags: [].}

  Fills `dest` with random bytes suitable for cryptographic use. If the call succeeds, returns `true`.

  If `dest` is empty, `urandom` immediately returns success, without calling the underlying operating system API.

  Warning: The code hasn't been audited by cryptography experts and is provided as-is without guarantees. Use at your own risks. For production systems we advise you to request an external audit.
  Source Edit

    proc urandom(size: Natural): seq[byte] {.inline, ...raises: [OSError], tags: [].}

  Returns random bytes suitable for cryptographic use.
  Warning: The code hasn't been audited by cryptography experts and is provided as-is without guarantees. Use at your own risks. For production systems we advise you to request an external audit.
  Source Edit