Module crypto.rng
Low-level Lua interface to the Linux Kernel Crypto API for synchronous Random Number Generators (RNG).
This module provides a new function to create RNG objects, which can then be used for generating random bytes.
Class RNG
rng:generate (num_bytes[, seed]) | Generates a specified number of random bytes, with optional seed. |
rng:getbytes (num_bytes) | Generates a specified number of random bytes. |
rng:info () | Retrieves information about the RNG algorithm. |
rng:reset ([seed]) | Resets the RNG. |
rng
new (algname) | Creates a new RNG object. |
Class RNG
RNG object methods.
These methods are available on RNG objects created by
crypto_rng.new()
.
- rng:generate (num_bytes[, seed])
-
Generates a specified number of random bytes, with optional seed.
Parameters:
- num_bytes integer The number of random bytes to generate.
- seed string Optional seed material to mix into the RNG. If nil or omitted, no explicit seed is used. (optional)
Returns:
-
string
A binary string containing the generated random bytes.
Raises:
Error on failure (e.g., allocation error, crypto API error). - rng:getbytes (num_bytes)
-
Generates a specified number of random bytes.
This function does not take an explicit seed as an argument.
Parameters:
- num_bytes integer The number of random bytes to generate.
Returns:
-
string
A binary string containing the generated random bytes.
Raises:
Error on failure (e.g., allocation error, crypto API error). - rng:info ()
-
Retrieves information about the RNG algorithm.
Returns:
-
table
A table containing algorithm information, e.g.,
{ driver_name = "...", seedsize = num }
. - rng:reset ([seed])
-
Resets the RNG.
This can be used to re-initialize the RNG, optionally with new seed material.
Parameters:
- seed string Optional seed material to mix into the RNG. If nil or omitted, the RNG will reseed from its default sources. (optional)
Raises:
Error on failure (e.g., crypto API error).
rng
- new (algname)
-
Creates a new RNG object.
This is the constructor function for the
crypto_rng
module.Parameters:
- algname string The name of the RNG algorithm (e.g., "stdrng", "drbgnoprctr_aes256"). Defaults to "stdrng" if nil or omitted.
Returns:
-
crypto_rng
The new RNG object.
Raises:
Error if the TFM object cannot be allocated/initialized.Usage:
local rng_mod = require("crypto.rng") local rng = rng_mod.new() -- Uses default "stdrng" local random_bytes = rng:generate(32) -- Get 32 random bytes