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 | SecRandomCopyBytes |
| 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
proc urandom(dest: var openArray[byte]): bool {....raises: [], tags: [],
forbids: [].}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.
proc urandom(size: Natural): seq[byte] {.inline, ...raises: [OSError], tags: [],
forbids: [].}
© 2006–2024 Andreas Rumpf
Licensed under the MIT License.
https://nim-lang.org/docs/sysrand.html