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
154       padding to the end of any string for which "length % 57" is a non-zero
155       value.
156
157       If an $eol is specified, the character(s) specified will be used as
158       line delimiters after every 76th character.  The default is "qq{\n}".
159       If you wish to eliminate line-break insertions, specify an empty
160       string: "q{}".
161
162   random_bytes_hex
163           my $random_bytes_as_hex = random_bytes_hex( $num_bytes );
164
165       Returns a string of hex digits representing the string of
166       $number_of_bytes random bytes.
167
168       It's worth mentioning that a hex (base16) representation of base256
169       data requires two digits for every byte requested. So "length(
170       random_bytes_hex( 16 ) )" will return 32, as it takes 32 hex digits to
171       represent 16 bytes.  Simple stuff, but better to mention it now than
172       forget and set a database field that's too narrow.
173
174   random_bytes_qp
175           my $random_bytes_qp           = random_bytes_qp( $num_bytes );
176           my $random_bytes_qp_formatted = random_bytes_qp( $num_bytes, $eol );
177
178       Produces a string of $num_bytes random bytes, using MIME Quoted
179       Printable encoding (as produced by MIME::QuotedPrint's "encode_qp"
180       function.  The default configuration uses "\n" as a line break after
181       every 76 characters, and the "binmode" setting is used to guarantee a
182       lossless round trip.  If no line break is wanted, pass an empty string
183       as $eol.
184

METHODS

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

CONFIGURATION

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

CAVEATS

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

INSTALLATION

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

SEE ALSO

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

AUTHOR

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

BUGS

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

SUPPORT

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

ACKNOWLEDGEMENTS

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