The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Sys::GetRandom - Perl interface to getrandom(2)

SYNOPSIS

    use Sys::GetRandom qw(getrandom random_bytes GRND_NONBLOCK GRND_RANDOM);
    my $n = getrandom($buf, $count, $flags, $offset);
    my $bytes = random_bytes($count);

DESCRIPTION

This module provides a Perl interface to the getrandom(2) call present on Linux and FreeBSD. It exports (on request) two functions and two constants.

Functions

getrandom SCALAR, LENGTH
getrandom SCALAR, LENGTH, FLAGS
getrandom SCALAR, LENGTH, FLAGS, OFFSET

Generates up to LENGTH bytes of random data and stores them in SCALAR. Returns the number of random bytes generated, or undef on error (in which case $! is also set).

By default, getrandom is equivalent to reading from /dev/urandom (but without accessing the file system or requiring the use of a file descriptor). If /dev/urandom has not been initialized yet, getrandom will block by default.

If /dev/urandom has been initialized and LENGTH is 256 or less, getrandom will atomically return the requested amount of random data (i.e. it will generate exactly LENGTH bytes of data and will not be interrupted by a signal). For larger values of LENGTH it may be interrupted by signals and either generate fewer random bytes than requested or fail with $! set to EINTR.

The FLAGS argument must be either 0 (the default value) or the bitwise OR of one or more of the following flags:

GRND_RANDOM

Read from the same source as /dev/random, not /dev/urandom (the default).

GRND_NONBLOCK

By default, getrandom will block if /dev/urandom has not been initialized yet or (with GRND_RANDOM) if there are no random bytes available in /dev/random. If the GRND_NONBLOCK flag is passed, it will fail immediately instead, returning undef and setting $! to EAGAIN.

By default, the generated bytes are placed at the beginning of SCALAR. You can pass a positive value for OFFSET to place them within the string, leaving the first OFFSET bytes unchanged.

random_bytes LENGTH

Generates and returns a string of LENGTH random bytes.

LENGTH must be between 0 and 256 (inclusive).

This is just a wrapper around getrandom with default flags.

AUTHOR

Lukas Mai, <lmai at web.de>

COPYRIGHT & LICENSE

Copyright 2023 Lukas Mai.

This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License.

See https://dev.perl.org/licenses/ for more information.