1Bytes::Random::Secure(3U)ser Contributed Perl DocumentatiBoyntes::Random::Secure(3)
2
3
4

NAME

6       Bytes::Random::Secure - Perl extension to generate
7       cryptographically-secure random bytes.
8

SYNOPSIS

10           use Bytes::Random::Secure qw(
11               random_bytes random_bytes_base64 random_bytes_hex
12           );
13
14           my $bytes = random_bytes(32); # A string of 32 random bytes.
15
16           my $bytes = random_string_from( 'abcde', 10 ); # 10 random a,b,c,d, and e's.
17
18           my $bytes_as_base64 = random_bytes_base64(57); # Base64 encoded rand bytes.
19
20           my $bytes_as_hex = random_bytes_hex(8); # Eight random bytes as hex digits.
21
22           my $bytes_as_quoted_printable = random_bytes_qp(100); # QP encoded bytes.
23
24
25           my $random = Bytes::Random::Secure->new(
26               Bits        => 64,
27               NonBlocking => 1,
28           ); # Seed with 64 bits, and use /dev/urandom (or other non-blocking).
29
30           my $bytes = $random->bytes(32); # A string of 32 random bytes.
31           my $long  = $random->irand;     # 32-bit random integer.
32

DESCRIPTION

34       Bytes::Random::Secure provides two interfaces for obtaining crypto-
35       quality random bytes.  The simple interface is built around plain
36       functions.  For greater control over the Random Number Generator's
37       seeding, there is an Object Oriented interface that provides much more
38       flexibility.
39
40       The "functions" interface provides functions that can be used any time
41       you need a string of a specific number of random bytes.  The random
42       bytes are available as simple strings, or as hex-digits, Quoted
43       Printable, or MIME Base64.  There are equivalent methods available from
44       the OO interface, plus a few others.
45
46       This module can be a drop-in replacement for Bytes::Random, with the
47       primary enhancement of using a cryptographic-quality random number
48       generator to create the random data.  The "random_bytes" function
49       emulates the user interface of Bytes::Random's function by the same
50       name.  But with Bytes::Random::Secure the random number generator comes
51       from Math::Random::ISAAC, and is suitable for cryptographic purposes.
52       The harder problem to solve is how to seed the generator.  This module
53       uses Crypt::Random::Seed to generate the initial seeds for
54       Math::Random::ISAAC.
55
56       In addition to providing random_bytes(), this module also provides
57       several functions not found in Bytes::Random: "random_string_from",
58       random_bytes_base64(), "random_bytes_hex", and "random_bytes_qp".
59
60       And finally, for those who need finer control over how
61       Crypt::Random::Seed generates its seed, there is an object oriented
62       interface with a constructor that facilitates configuring the seeding
63       process, while providing methods that do everything the "functions"
64       interface can do (truth be told, the functions interface is just a thin
65       wrapper around the OO version, with some sane defaults selected).  The
66       OO interface also provides an "irand" method, not available through the
67       functions interface.
68

RATIONALE

70       There are many uses for cryptographic quality randomness.  This module
71       aims to provide a generalized tool that can fit into many applications
72       while providing a minimal dependency chain, and a user interface that
73       is simple.  You're free to come up with your own use-cases, but there
74       are several obvious ones:
75
76       •   Creating temporary passphrases (random_string_from()).
77
78       •   Generating per-account random salt to be hashed along with
79           passphrases (and stored alongside them) to prevent rainbow table
80           attacks.
81
82       •   Generating a secret that can be hashed along with a cookie's
83           session content to prevent cookie forgeries.
84
85       •   Building raw cryptographic-quality pseudo-random data sets for
86           testing or sampling.
87
88       •   Feeding secure key-gen utilities.
89
90       Why use this module?  This module employs several well-designed CPAN
91       tools to first generate a strong random seed, and then to instantiate a
92       high quality random number generator based on the seed.  The code in
93       this module really just glues together the building blocks.  However,
94       it has taken a good deal of research to come up with what I feel is a
95       strong tool-chain that isn't going to fall back to a weak state on some
96       systems.  The interface is designed with simplicity in mind, to
97       minimize the potential for misconfiguration.
98

EXPORTS

100       By default "random_bytes" is the only function exported.  Optionally
101       "random_string_from", "random_bytes_base64", "random_bytes_hex", and
102       "random_bytes_qp" may be exported.
103

FUNCTIONS

105       The functions interface seeds the ISAAC generator on first use with a
106       256 bit seed that uses Crypt::Random::Seed's default configuration as a
107       strong random seed source.
108
109   random_bytes
110           my $random_bytes = random_bytes( 512 );
111
112       Returns a string containing as many random bytes as requested.
113       Obviously the string isn't useful for display, as it can contain any
114       byte value from 0 through 255.
115
116       The parameter is a byte-count, and must be an integer greater or equal
117       to zero.
118
119   random_string_from
120           my $random_bytes = random_string_from( $bag, $length );
121           my $random_bytes = random_string_from( 'abc', 50 );
122
123       $bag is a string of characters from which "random_string_from" may
124       choose in building a random string.  We call it a 'bag', because it's
125       permissible to have repeated chars in the bag (if not, we could call it
126       a set).  Repeated digits get more weight.  For example,
127       "random_string_from( 'aab', 1 )" would have a 66.67% chance of
128       returning an 'a', and a 33.33% chance of returning a 'b'.  For
129       unweighted distribution, ensure there are no duplicates in $bag.
130
131       This isn't a "draw and discard", or a permutation algorithm; each
132       character selected is independent of previous or subsequent selections;
133       duplicate selections are possible by design.
134
135       Return value is a string of size $length, of characters chosen at
136       random from the 'bag' string.
137
138       It is perfectly legal to pass a Unicode string as the "bag", and in
139       that case, the yield will include Unicode characters selected from
140       those passed in via the bag string.
141
142       This function is useful for random string generation such as temporary
143       random passwords.
144
145   random_bytes_base64
146           my $random_bytes_b64           = random_bytes_base64( $num_bytes );
147           my $random_bytes_b64_formatted = random_bytes_base64( $num_bytes, $eol );
148
149       Returns a MIME Base64 encoding of a string of $number_of_bytes random
150       bytes.  Note, it should be obvious, but is worth mentioning that a
151       base64 encoding of base256 data requires more digits to represent the
152       bytes requested.  The actual number of digits required, including
153       padding is 4(n/3).  Furthermore, the Base64 standard is to add padding
154       to the end of any string for which "length % 57" is a non-zero value.
155
156       If an $eol is specified, the character(s) specified will be used as
157       line delimiters after every 76th character.  The default is "qq{\n}".
158       If you wish to eliminate line-break insertions, specify an empty
159       string: "q{}".
160
161   random_bytes_hex
162           my $random_bytes_as_hex = random_bytes_hex( $num_bytes );
163
164       Returns a string of hex digits representing the string of
165       $number_of_bytes random bytes.
166
167       It's worth mentioning that a hex (base16) representation of base256
168       data requires two digits for every byte requested. So "length(
169       random_bytes_hex( 16 ) )" will return 32, as it takes 32 hex digits to
170       represent 16 bytes.  Simple stuff, but better to mention it now than
171       forget and set a database field that's too narrow.
172
173   random_bytes_qp
174           my $random_bytes_qp           = random_bytes_qp( $num_bytes );
175           my $random_bytes_qp_formatted = random_bytes_qp( $num_bytes, $eol );
176
177       Produces a string of $num_bytes random bytes, using MIME Quoted
178       Printable encoding (as produced by MIME::QuotedPrint's "encode_qp"
179       function.  The default configuration uses "\n" as a line break after
180       every 76 characters, and the "binmode" setting is used to guarantee a
181       lossless round trip.  If no line break is wanted, pass an empty string
182       as $eol.
183

METHODS

185       The Object Oriented interface provides methods that mirror the
186       "functions" interface.  However, the OO interface offers the advantage
187       that the user can control how many bits of entropy are used in seeding,
188       and even how Crypt::Random::Seed is configured.
189
190   new
191           my $random = Bytes::Random::Secure->new( Bits => 512 );
192           my $bytes  = $random->bytes( 32 );
193
194       The constructor is used to specify how the ISAAC generator is seeded.
195       Future versions may also allow for alternate CSPRNGs to be selected.
196       If no parameters are passed the default configuration specifies 256
197       bits for the seed.  The rest of the default configuration accepts the
198       Crypt::Random::Seed defaults, which favor the strongest operating
199       system provided entropy source, which in many cases may be "blocking".
200
201       CONSTRUCTOR PARAMETERS
202
203       Bits
204
205           my $random = Bytes::Random::Secure->new( Bits => 128 );
206
207       The "Bits" parameter specifies how many bits (rounded up to nearest
208       multiple of 32) will be used in seeding the ISAAC random number
209       generator.  The default is 256 bits of entropy.  But in some cases it
210       may not be necessary, or even wise to pull so many bits of entropy out
211       of "/dev/random" (a blocking source).
212
213       Any value between 64 and 8192 will be accepted. If an out-of-range
214       value is specified, or a value that is not a multiple of 32, a warning
215       will be generated and the parameter will be rounded up to the nearest
216       multiple of 32 within the range of 64 through 8192 bits.  So if 16384
217       is specified, you will get 8192.  If 33 is specified, you will get 64.
218
219       Note: In the Perlish spirit of "no arbitrary limits", the maximum
220       number of bits this module accepts is 8192, which is the maximum number
221       that ISAAC can utilize.  But just because you can specify a seed of
222       8192 bits doesn't mean you ought to, much less need to.  And if you do,
223       you probably want to use the "NonBlocking" option, discussed below.
224       8192 bits is a lot to ask from a blocking source such as "/dev/random",
225       and really anything beyond 512 bits in the seed is probably wasteful.
226
227       PRNG
228
229       Reserved for future use.  Eventually the user will be able to select
230       other RNGs aside from Math::Random::ISAAC.
231
232       Unique
233
234       Reserved for future use.
235
236       Other Crypt::Random::Seed Configuration Parameters
237
238       For additional seeding control, refer to the POD for
239       Crypt::Random::Seed.  By supplying a Crypt::Random::Seed parameter to
240       Bytes::Random::Secure's constructor, it will be passed through to
241       Crypt::Random::Seed.  For example:
242
243           my $random = Bytes::Random::Secure->new( NonBlocking => 1, Bits => 64 );
244
245       In this example, "Bits" is used internally, while "NonBlocking" is
246       passed through to Crypt::Random::Seed.
247
248   bytes
249           my $random_bytes = $random->bytes(1024);
250
251       This works just like the "random_bytes" function.
252
253   string_from
254           my $random_string = $random->string_from( 'abcdefg', 10 );
255
256       Just like "random_string_from": Returns a string of random octets
257       selected from the "Bag" string (in this case ten octets from
258       'abcdefg').
259
260   bytes_hex
261           my $random_hex = $random->bytes_hex(12);
262
263       Identical in function to "random_bytes_hex".
264
265   bytes_base64
266           my $random_base64 = $random->bytes_base64( 32, EOL => "\n" );
267
268       Identical in function to "random_bytes_base64".
269
270   bytes_qp
271           my $random_qp = $random->bytes_qp( 80 );
272
273       You guessed it: Identical in function to "random_bytes_qp".
274
275   irand
276           my $unsigned_long = $random->irand;
277
278       Returns a random 32-bit unsigned integer.  The value will satisfy "0 <=
279       x <= 2**32-1".  This functionality is only available through the OO
280       interface.
281
282   shuffle
283           my $aref_shuffled = $random->shuffle($aref);
284
285       Shuffles the contents of a reference to an array in sitiu, and returns
286       the same reference.
287
288       List::Util, which ships with Perl, includes "shuffle" function. But
289       that function is flawed in two ways. First, from a cryptographic
290       standpoint, it uses Perl's "rand", which is not a CSPRNG, and therefore
291       is inadequate.
292
293       Second, because Perl's rand has an internal state of just 32 bits, it
294       cannot possibly generate all permutations of arrays containing 13 or
295       more elements.
296
297       This module's "shuffle" uses a CSPRNG, and also benefits from large
298       seeds and a huge internal state. ISAAC can be seeded with up to 8192
299       bits, yielding 2^8192 possible initial states, and 2^8288 possible
300       internal states. A seed of 8192 bits will assure that for arrays of up
301       to 966 elements every permutation is accessible.
302

CONFIGURATION

304       Bytes::Random::Secure's interface tries to keep it simple.  There is
305       generally nothing to configure.  This design, eliminates much of the
306       potential for diminishing the quality of the random byte stream through
307       misconfiguration.  The ISAAC algorithm is used as our factory, seeded
308       with a strong source.
309
310       There may be times when the default seed characteristics carry too
311       heavy a burden on system resources.  The default seed for the functions
312       interface is 256 bits of entropy taken from /dev/random (a blocking
313       source on many systems), or via API calls on Windows.  The default seed
314       size for the OO interface is also 256 bits. If /dev/random should
315       become depleted at the time that this module attempts to seed the ISAAC
316       generator, there could be delay while additional system entropy is
317       generated.  If this is a problem, it is possible to override the
318       default seeding characteristics using the OO interface instead of the
319       functions interface.  However, under most circumstances, this
320       capability may be safely ignored.
321
322       Beginning with Bytes::Random::Secure version 0.20, Crypt::Random::Seed
323       provides our strong seed (previously it was Crypt::Random::Source).
324       This module gives us excellent "strong source" failsafe behavior, while
325       keeping the non-core dependencies to a bare minimum.  Best of all, it
326       performs well across a wide variety of platforms, and is compatible
327       with Perl versions back through 5.6.0.
328
329       And as mentioned earlier in this document, there may be circumstances
330       where the performance of the operating system's strong random source is
331       prohibitive from using the module's default seeding configuration.  Use
332       the OO interface instead, and read the documentation for
333       Crypt::Random::Seed to learn what options are available.
334
335       Prior to version 0.20, a heavy dependency chain was required for
336       reliably and securely seeding the ISAAC generator.  Earlier versions
337       required Crypt::Random::Source, which in turn required Any::Moose.
338       Thanks to Dana Jacobsen's new Crypt::Random::Seed module, this
339       situation has been resolved.  So if you're looking for a secure random
340       bytes solution that "just works" portably, and on Perl versions as far
341       back as 5.6.0, you've come to the right place.  Users of older versions
342       of this module are encouraged to update to version 0.20 or higher to
343       benefit from the improved user interface and lighter dependency chain.
344
345   OPTIONAL (RECOMMENDED) DEPENDENCY
346       If performance is a consideration, you may also install
347       Math::Random::ISAAC::XS. Bytes::Random::Secure's random number
348       generator uses Math::Random::ISAAC.  That module implements the ISAAC
349       algorithm in pure Perl.  However, if you install
350       Math::Random::ISAAC::XS, you get the same algorithm implemented in
351       C/XS, which will provide better performance.  If you need to produce
352       your random bytes more quickly, simply installing
353       Math::Random::ISAAC::XS will result in it automatically being used, and
354       a pretty good performance improvement will coincide.
355

CAVEATS

357   FORK AND THREAD SAFETY
358       When programming for parallel computation, avoid the "functions"
359       interface do use the Object Oriented interface, and create a unique
360       "Bytes::Random::Secure" object within each process or thread.
361       Bytes::Random::Secure uses a CSPRNG, and sharing the same RNG between
362       threads or processes will share the same seed and the same starting
363       point.  This is probably not what one would want to do. By
364       instantiating the B::R::S object after forking or creating threads, a
365       unique randomness stream will be created per thread or process.
366
367   STRONG RANDOMNESS
368       It's easy to generate weak pseudo-random bytes.  It's also easy to
369       think you're generating strong pseudo-random bytes when really you're
370       not.  And it's hard to test for pseudo-random cryptographic acceptable
371       quality.  There are many high quality random number generators that are
372       suitable for statistical purposes, but not necessarily up to the rigors
373       of cryptographic use.
374
375       Assuring strong (ie, secure) random bytes in a way that works across a
376       wide variety of platforms is also challenging.  A primary goal for this
377       module is to provide cryptographically secure pseudo-random bytes.  A
378       secondary goal is to provide a simple user experience (thus reducing
379       the propensity for getting it wrong).  A tertiary goal is to minimize
380       the dependencies required to achieve the primary and secondary goals,
381       to the extent that is practical.
382
383   ISAAC
384       The ISAAC algorithm is considered to be a cryptographically strong
385       pseudo-random number generator.  There are 1.0e2466 initial states.
386       The best known attack for discovering initial state would theoretically
387       take a complexity of approximately 4.67e1240, which has no practical
388       impact on ISAAC's security.  Cycles are guaranteed to have a minimum
389       length of 2**40, with an average cycle of 2**8295.  Because there is no
390       practical attack capable of discovering initial state, and because the
391       average cycle is so long, it's generally unnecessary to re-seed a
392       running application.  The results are uniformly distributed, unbiased,
393       and unpredictable unless the seed is known.
394
395       To confirm the quality of the CSPRNG, this module's test suite
396       implements the FIPS-140-1
397       <http://csrc.nist.gov/publications/fips/fips1401.htm> tests for strong
398       random number generators.  See the comments in "t/27-fips140-1.t" for
399       details.
400
401   DEPENDENCIES
402       To keep the dependencies as light as possible this module uses some
403       ideas from Math::Random::Secure.  That module is an excellent resource,
404       but implements a broader range of functionality than is needed here.
405       So we just borrowed from it.
406
407       The primary source of random data in this module comes from the
408       excellent Math::Random::ISAAC.  To be useful and secure, even
409       Math::Random::ISAAC needs a cryptographically sound seed, which we
410       derive from Crypt::Random::Seed.  There are no known weaknesses in the
411       ISAAC algorithm.  And Crypt::Random::Seed does a very good job of
412       preventing fall-back to weak seed sources.
413
414       This module requires Perl 5.6 or newer.  The module also uses a number
415       of core modules, some of which require newer versions than those
416       contemporary with 5.6.  Unicode support in "random_string_from" is best
417       with Perl 5.8.9 or newer.  See the INSTALLATION section in this
418       document for details.
419
420       If Test::Warn is installed, test coverage is 100%.  For those who don't
421       want to bother installing Test::Warn, you can just take our word for
422       it.  It's an optional installation dependency.
423
424   BLOCKING ENTROPY SOURCE
425       It is possible (and has been seen in testing) that the system's random
426       entropy source might not have enough entropy in reserve to generate the
427       seed requested by this module without blocking.  If you suspect that
428       you're a victim of blocking from reads on "/dev/random", one option is
429       to manipulate the random seed configuration by using the object
430       oriented interface.
431
432       This module seeds as lazily as possible so that using the module, and
433       even instantiating a Bytes::Random::Secure object will not trigger
434       reads from "/dev/random".  Only the first time the object is used to
435       deliver random bytes will the RNG be seeded.  Long-running scripts may
436       prefer to force early seeding as close to start-up time as possible,
437       rather than allowing it to happen later in a program's run-time.  This
438       can be achieved simply by invoking any of the functions or methods that
439       return a random byte.  As soon as a random byte is requested for the
440       first time, the CSPRNG will be seeded.
441
442   UNICODE SUPPORT
443       The "random_string_from" function, and "string_from" method permit the
444       user to pass a "bag" (or source) string containing Unicode characters.
445       For any modern Perl version, this will work just as you would hope.
446       But some versions of Perl older than 5.8.9 exhibited varying degrees of
447       bugginess in their handling of Unicode.  If you're depending on the
448       Unicode features of this module while using Perl versions older than
449       5.8.9 be sure to test thoroughly, and don't be surprised when the
450       outcome isn't as expected.  ...this is to be expected.  Upgrade.
451
452       No other functions or methods in this module get anywhere near Perl's
453       Unicode features.  So as long as you're not passing Unicode source
454       strings to "random_string_from", you have nothing to worry about, even
455       if you're using Perl 5.6.0.
456
457   MODULO BIAS
458       Care is taken so that there is no modulo bias in the randomness
459       returned either by "random_bytes" or its siblings, nor by
460       "random_string_from".  As a matter if fact, this is exactly why the
461       "random_string_from" function is useful.  However, the algorithm to
462       eliminate modulo bias can impact the performance of the
463       "random_string_from" function. Any time the length of the bag string is
464       significantly less than the nearest greater or equal factor of 2**32,
465       performance will degrade.  Unfortunately there is no known algorithm
466       that improves upon this situation.  Fortunately, for sanely sized
467       strings, it's a minor issue.  To put it in perspective, even in the
468       case of passing a "bag" string of length 2**31 (which is huge), the
469       expected time to return random bytes will only double.  Given that the
470       entire Unicode range is just over a million possible code-points, it
471       seems unlikely that the normal use case would ever have to be concerned
472       with the performance of the "random_string_from" function.
473

INSTALLATION

475       This module should install without any fuss on modern versions of Perl.
476       For older Perl versions (particularly 5.6 and early 5.8.x's), it may be
477       necessary to update your CPAN installer to a more modern version before
478       installing this this module.
479
480       Another alternative for those with old Perl versions who don't want to
481       update their CPAN installer (You must know you're crazy, right?):
482       Review "Makefile.PL" and assure that you've got the dependencies listed
483       under "PREREQ_PM" and "BUILD_REQUIRES", in at least the minimum
484       versions specified.  Then proceed as usual.
485
486       This module only has two non-Core dependencies.  But it does expect
487       that some of the Core dependencies are newer than those supplied with
488       5.6 or early 5.8's.  If you keep your CPAN installer up-to-date, you
489       shouldn't have to think about this, as it will usually just "do the
490       right thing", pulling in newer dependency versions as directed by the
491       module's META files.
492
493       Test coverage for Bytes::Random::Secure is 100% (per Devel::Cover) on
494       any system that has Test::Warn installed.  But to keep the module
495       light-weight, Test::Warn is not dragged in by default at installation
496       time.
497

SEE ALSO

499       Math::Random::Secure and Crypt::Random provide strong CSPRINGs and even
500       more configuration options, but come with hefty toolchains.
501
502       Bytes::Random::Secure::Tiny is a stand-alone adaptation of
503       Bytes::Random::Secure with no dependencies. It will, however, detect if
504       Math::Random::ISAAC, Math::Random::ISAAC::XS, and Crypt::Random::Seed
505       are installed on the target system, and if they are, it quietly
506       upgrades to using them.
507

AUTHOR

509       David Oswald "<davido [at] cpan (dot) org>"
510

BUGS

512       Please report any bugs or feature requests to "bug-bytes-random-secure
513       at rt.cpan.org", or through the web interface at
514       <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Bytes-Random-Secure>.
515       I will be notified, and then you'll automatically be notified of
516       progress on your bug as I make changes.
517

SUPPORT

519       You can find documentation for this module with the perldoc command.
520
521           perldoc Bytes::Random::Secure
522
523       You can also look for information at:
524
525       •   Github Repo: <https://github.com/daoswald/Bytes-Random-Secure>
526
527       •   RT: CPAN's request tracker (report bugs here)
528
529           <http://rt.cpan.org/NoAuth/Bugs.html?Dist=Bytes-Random-Secure>
530
531       •   AnnoCPAN: Annotated CPAN documentation
532
533           <http://annocpan.org/dist/Bytes-Random-Secure>
534
535       •   CPAN Ratings
536
537           <http://cpanratings.perl.org/d/Bytes-Random-Secure>
538
539       •   Search CPAN
540
541           <http://search.cpan.org/dist/Bytes-Random-Secure/>
542

ACKNOWLEDGEMENTS

544       Dana Jacobsen ( <dana@acm.org> ) for his work that led to
545       Crypt::Random::Seed, thereby significantly reducing the dependencies
546       while improving the portability and backward compatibility of this
547       module.  Also for providing a patch to this module that greatly
548       improved the performance of "random_bytes".
549
550       Dana Jacosen also provided extensive input, code reviews, and testing
551       that helped to guide the direction this module has taken.  The code for
552       the FIPS-140-1 tests was taken directly from Crypt::Random::TESHA2.
553       Thanks!
554
555       Bytes::Random for implementing a nice, simple interface that this
556       module patterns itself after.
557
559       Copyright 2012 David Oswald.
560
561       This program is free software; you can redistribute it and/or modify it
562       under the terms of either: the GNU General Public License as published
563       by the Free Software Foundation; or the Artistic License.
564
565       See http://dev.perl.org/licenses/ for more information.
566
567
568
569perl v5.36.0                      2023-01-20          Bytes::Random::Secure(3)
Impressum