Bytes::Random::Secure (3)
Leading comments
Automatically generated by Pod::Man 2.27 (Pod::Simple 3.28) Standard preamble: ========================================================================
NAME
Bytes::Random::Secure - Perl extension to generate cryptographically-secure random bytes.SYNOPSIS
use Bytes::Random::Secure qw( random_bytes random_bytes_base64 random_bytes_hex ); my $bytes = random_bytes(32); # A string of 32 random bytes. my $bytes = random_string_from( 'abcde', 10 ); # 10 random a,b,c,d, and e's. my $bytes_as_base64 = random_bytes_base64(57); # Base64 encoded rand bytes. my $bytes_as_hex = random_bytes_hex(8); # Eight random bytes as hex digits. my $bytes_as_quoted_printable = random_bytes_qp(100); # QP encoded bytes. my $random = Bytes::Random::Secure->new( Bits => 64, NonBlocking => 1, ); # Seed with 64 bits, and use /dev/urandom (or other non-blocking). my $bytes = $random->bytes(32); # A string of 32 random bytes. my $long = $random->irand; # 32-bit random integer.
DESCRIPTION
Bytes::Random::Secure provides two interfaces for obtaining crypto-quality random bytes. The simple interface is built around plain functions. For greater control over the Random Number Generator's seeding, there is an Object Oriented interface that provides much more flexibility.The ``functions'' interface provides functions that can be used any time you need a string of a specific number of random bytes. The random bytes are available as simple strings, or as hex-digits, Quoted Printable, or
This module can be a drop-in replacement for Bytes::Random, with the primary enhancement of using a cryptographic-quality random number generator to create the random data. The "random_bytes" function emulates the user interface of Bytes::Random's function by the same name. But with Bytes::Random::Secure the random number generator comes from Math::Random::ISAAC, and is suitable for cryptographic purposes. The harder problem to solve is how to seed the generator. This module uses Crypt::Random::Seed to generate the initial seeds for Math::Random::ISAAC.
In addition to providing "random_bytes()", this module also provides several functions not found in Bytes::Random: "random_string_from", "random_bytes_base64()", "random_bytes_hex", and "random_bytes_qp".
And finally, for those who need finer control over how Crypt::Random::Seed generates its seed, there is an object oriented interface with a constructor that facilitates configuring the seeding process, while providing methods that do everything the ``functions'' interface can do (truth be told, the functions interface is just a thin wrapper around the
RATIONALE
There are many uses for cryptographic quality randomness. This module aims to provide a generalized tool that can fit into many applications while providing a minimal dependency chain, and a user interface that is simple. You're free to come up with your own use-cases, but there are several obvious ones:- *
- Creating temporary passphrases ("random_string_from()").
- *
- Generating per-account random salt to be hashed along with passphrases (and stored alongside them) to prevent rainbow table attacks.
- *
- Generating a secret that can be hashed along with a cookie's session content to prevent cookie forgeries.
- *
- Building raw cryptographic-quality pseudo-random data sets for testing or sampling.
- *
- Feeding secure key-gen utilities.
Why use this module? This module employs several well-designed
EXPORTS
By default "random_bytes" is the only function exported. Optionally "random_string_from", "random_bytes_base64", "random_bytes_hex", and "random_bytes_qp" may be exported.FUNCTIONS
The functions interface seeds therandom_bytes
my $random_bytes = random_bytes( 512 );
Returns a string containing as many random bytes as requested. Obviously the string isn't useful for display, as it can contain any byte value from 0 through 255.
The parameter is a byte-count, and must be an integer greater or equal to zero.
random_string_from
my $random_bytes = random_string_from( $bag, $length ); my $random_bytes = random_string_from( 'abc', 50 );
$bag is a string of characters from which "random_string_from" may choose in building a random string. We call it a 'bag', because it's permissible to have repeated chars in the bag (if not, we could call it a set). Repeated digits get more weight. For example, "random_string_from( 'aab', 1 )" would have a 66.67% chance of returning an 'a', and a 33.33% chance of returning a 'b'. For unweighted distribution, ensure there are no duplicates in $bag.
This isn't a ``draw and discard'', or a permutation algorithm; each character selected is independent of previous or subsequent selections; duplicate selections are possible by design.
Return value is a string of size $length, of characters chosen at random from the 'bag' string.
It is perfectly legal to pass a Unicode string as the ``bag'', and in that case, the yield will include Unicode characters selected from those passed in via the bag string.
This function is useful for random string generation such as temporary random passwords.
random_bytes_base64
my $random_bytes_b64 = random_bytes_base64( $num_bytes ); my $random_bytes_b64_formatted = random_bytes_base64( $num_bytes, $eol );
Returns a
If an $eol is specified, the character(s) specified will be used as line delimiters after every 76th character. The default is "qq{\n}". If you wish to eliminate line-break insertions, specify an empty string: "q{}".
random_bytes_hex
my $random_bytes_as_hex = random_bytes_hex( $num_bytes );
Returns a string of hex digits representing the string of $number_of_bytes random bytes.
It's worth mentioning that a hex (base16) representation of base256 data requires two digits for every byte requested. So "length( random_bytes_hex( 16 ) )" will return 32, as it takes 32 hex digits to represent 16 bytes. Simple stuff, but better to mention it now than forget and set a database field that's too narrow.
random_bytes_qp
my $random_bytes_qp = random_bytes_qp( $num_bytes ); my $random_bytes_qp_formatted = random_bytes_qp( $num_bytes, $eol );
Produces a string of $num_bytes random bytes, using
METHODS
The Object Oriented interface provides methods that mirror the ``functions'' interface. However, thenew
my $random = Bytes::Random::Secure->new( Bits => 512 ); my $bytes = $random->bytes( 32 );
The constructor is used to specify how the
Bits
my $random = Bytes::Random::Secure->new( Bits => 128 );
The "Bits" parameter specifies how many bits (rounded up to nearest multiple of 32) will be used in seeding the
Any value between 64 and 8192 will be accepted. If an out-of-range value is specified, or a value that is not a multiple of 32, a warning will be generated and the parameter will be rounded up to the nearest multiple of 32 within the range of 64 through 8192 bits. So if 16384 is specified, you will get 8192. If 33 is specified, you will get 64.
Note: In the Perlish spirit of "no arbitrary limits", the maximum number of bits this module accepts is 8192, which is the maximum number that
Reserved for future use. Eventually the user will be able to select other RNGs aside from Math::Random::ISAAC.
Unique
Reserved for future use.
Other Crypt::Random::Seed Configuration Parameters
For additional seeding control, refer to the
my $random = Bytes::Random::Secure->new( NonBlocking => 1, Bits => 64 );
In this example, "Bits" is used internally, while "NonBlocking" is passed through to Crypt::Random::Seed.
bytes
my $random_bytes = $random->bytes(1024);
This works just like the "random_bytes" function.
string_from
my $random_string = $random->string_from( 'abcdefg', 10 );
Just like "random_string_from": Returns a string of random octets selected from the ``Bag'' string (in this case ten octets from 'abcdefg').
bytes_hex
my $random_hex = $random->bytes_hex(12);
Identical in function to "random_bytes_hex".
bytes_base64
my $random_base64 = $random->bytes_base64( 32, EOL => "\n" );
Identical in function to "random_bytes_base64".
bytes_qp
my $random_qp = $random->bytes_qp( 80 );
You guessed it: Identical in function to "random_bytes_qp".
irand
my $unsigned_long = $random->irand;
Returns a random 32-bit unsigned integer. The value will satisfy "0 <= x <= 2**32-1". This functionality is only available through the
CONFIGURATION
Bytes::Random::Secure's interface tries to keep it simple. There is generally nothing to configure. This design, eliminates much of the potential for diminishing the quality of the random byte stream through misconfiguration. TheThere may be times when the default seed characteristics carry too heavy a burden on system resources. The default seed for the functions interface is 256 bits of entropy taken from /dev/random (a blocking source on many systems), or via
Beginning with Bytes::Random::Secure version 0.20, Crypt::Random::Seed provides our strong seed (previously it was Crypt::Random::Source). This module gives us excellent ``strong source'' failsafe behavior, while keeping the non-core dependencies to a bare minimum. Best of all, it performs well across a wide variety of platforms, and is compatible with Perl versions back through 5.6.0.
And as mentioned earlier in this document, there may be circumstances where the performance of the operating system's strong random source is prohibitive from using the module's default seeding configuration. Use the
Prior to version 0.20, a heavy dependency chain was required for reliably and securely seeding the
OPTIONAL (RECOMMENDED) DEPENDENCY
If performance is a consideration, you may also install
Math::Random::ISAAC::XS. Bytes::Random::Secure's random number generator
uses Math::Random::ISAAC. That module implements the CAVEATS
FORK AND THREAD SAFETY
When programming for parallel computation, avoid the ``functions'' interface do
use the Object Oriented interface, and create a unique "Bytes::Random::Secure"
object within each process or thread. Bytes::Random::Secure uses
a STRONG RANDOMNESS
It's easy to generate weak pseudo-random bytes. It's also easy to think you're
generating strong pseudo-random bytes when really you're not. And it's hard to
test for pseudo-random cryptographic acceptable quality. There are many high
quality random number generators that are suitable for statistical purposes,
but not necessarily up to the rigors of cryptographic use.
Assuring strong (ie, secure) random bytes in a way that works across a wide variety of platforms is also challenging. A primary goal for this module is to provide cryptographically secure pseudo-random bytes. A secondary goal is to provide a simple user experience (thus reducing the propensity for getting it wrong). A tertiary goal is to minimize the dependencies required to achieve the primary and secondary goals, to the extent that is practical.
ISAAC
The To confirm the quality of the
DEPENDENCIES
To keep the dependencies as light as possible this module uses some ideas from
Math::Random::Secure. That module is an excellent resource, but implements
a broader range of functionality than is needed here. So we just borrowed
from it.
The primary source of random data in this module comes from the excellent Math::Random::ISAAC. To be useful and secure, even Math::Random::ISAAC needs a cryptographically sound seed, which we derive from Crypt::Random::Seed. There are no known weaknesses in the
This module requires Perl 5.6 or newer. The module also uses a number of core modules, some of which require newer versions than those contemporary with 5.6. Unicode support in "random_string_from" is best with Perl 5.8.9 or newer. See the
If Test::Warn is installed, test coverage is 100%. For those who don't want to bother installing Test::Warn, you can just take our word for it. It's an optional installation dependency.
BLOCKING ENTROPY SOURCE
It is possible (and has been seen in testing) that the system's random
entropy source might not have enough entropy in reserve to generate the seed
requested by this module without blocking. If you suspect that you're a victim
of blocking from reads on "/dev/random", one option is to manipulate the
random seed configuration by using the object oriented interface.
This module seeds as lazily as possible so that using the module, and even instantiating a Bytes::Random::Secure object will not trigger reads from "/dev/random". Only the first time the object is used to deliver random bytes will the
UNICODE SUPPORT
The "random_string_from" function, and "string_from" method permit the user
to pass a ``bag'' (or source) string containing Unicode characters. For any
modern Perl version, this will work just as you would hope. But some versions
of Perl older than 5.8.9 exhibited varying degrees of bugginess in their
handling of Unicode. If you're depending on the Unicode features of this
module while using Perl versions older than 5.8.9 be sure to test thoroughly,
and don't be surprised when the outcome isn't as expected. ...this is to be
expected. Upgrade.
No other functions or methods in this module get anywhere near Perl's Unicode features. So as long as you're not passing Unicode source strings to "random_string_from", you have nothing to worry about, even if you're using Perl 5.6.0.
MODULO BIAS
Care is taken so that there is no modulo bias in the randomness returned
either by "random_bytes" or its siblings, nor by "random_string_from". As a
matter if fact, this is exactly why the "random_string_from" function is
useful. However, the algorithm to eliminate modulo bias can impact the
performance of the "random_string_from" function. Any time the length of the
bag string is significantly less than the nearest greater or equal factor
of 2**32, performance will degrade. Unfortunately there is no known algorithm
that improves upon this situation. Fortunately, for sanely sized strings, it's
a minor issue. To put it in perspective, even in the case of passing a ``bag''
string of length 2**31 (which is huge), the expected time to return random
bytes will only double. Given that the entire Unicode range is just over a
million possible code-points, it seems unlikely that the normal use case would
ever have to be concerned with the performance of the "random_string_from"
function.
INSTALLATION
This module should install without any fuss on modern versions of Perl. For older Perl versions (particularly 5.6 and early 5.8.x's), it may be necessary to update yourAnother alternative for those with old Perl versions who don't want to update their
This module only has two non-Core dependencies. But it does expect that some of the Core dependencies are newer than those supplied with 5.6 or early 5.8's. If you keep your
Test coverage for Bytes::Random::Secure is 100% (per Devel::Cover) on any system that has Test::Warn installed. But to keep the module light-weight, Test::Warn is not dragged in by default at installation time.
AUTHOR
David Oswald "<davido [at] cpan (dot) org>"BUGS
Please report any bugs or feature requests to "bug-bytes-random-secure at rt.cpan.org", or through the web interface at <rt.cpan.org/NoAuth/ReportBug.html?Queue=Bytes-Random-Secure>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.SUPPORT
You can find documentation for this module with the perldoc command.
perldoc Bytes::Random::Secure
You can also look for information at:
- *
- Github Repo: <github.com/daoswald/Bytes-Random-Secure>
- *
-
RT: CPAN's request tracker (report bugs here)
- *
-
AnnoCPAN: Annotated CPANdocumentation
- *
-
CPANRatings
- *
-
Search CPAN
ACKNOWLEDGEMENTS
Dana Jacobsen ( <dana@acm.org> ) for his work that led to Crypt::Random::Seed, thereby significantly reducing the dependencies while improving the portability and backward compatibility of this module. Also for providing a patch to this module that greatly improved the performance of "random_bytes".Dana Jacosen also provided extensive input, code reviews, and testing that helped to guide the direction this module has taken. The code for the
Bytes::Random for implementing a nice, simple interface that this module patterns itself after.
LICENSE AND COPYRIGHT
Copyright 2012 David Oswald.This program is free software; you can redistribute it and/or modify it under the terms of either: the
See dev.perl.org/licenses for more information.