File Coverage

blib/lib/Bytes/Random/Secure.pm
Criterion Covered Total %
statement 169 180 93.8
branch 60 66 90.9
condition 6 6 100.0
subroutine 41 41 100.0
pod 13 13 100.0
total 289 306 94.4


line stmt bran cond sub pod time code
1             ## no critic (constant,unpack)
2              
3             package Bytes::Random::Secure;
4              
5 9     9   245506 use strict;
  9         22  
  9         1735  
6 9     9   59 use warnings;
  9         17  
  9         349  
7 9     9   261 use 5.006000;
  9         31  
8 9     9   53 use Carp;
  9         13  
  9         1067  
9 9     9   137 use Scalar::Util qw( looks_like_number );
  9         14  
  9         1053  
10              
11 9     9   7087 use Math::Random::ISAAC;
  9         18498  
  9         427  
12 9     9   7461 use Crypt::Random::Seed;
  9         38071  
  9         1058  
13              
14 9     9   9696 use MIME::Base64 'encode_base64';
  9         6726  
  9         971  
15 9     9   5612 use MIME::QuotedPrint 'encode_qp';
  9         2310  
  9         608  
16              
17 9     9   165 use Exporter;
  9         17  
  9         1039  
18             our @ISA = qw( Exporter );
19              
20             our @EXPORT_OK = qw(
21             random_bytes random_bytes_hex
22             random_bytes_base64 random_bytes_qp
23             random_string_from
24             );
25              
26             our @EXPORT = qw( random_bytes ); ## no critic(export)
27              
28             our $VERSION = '0.29';
29              
30             # Seed size: 256 bits is eight 32-bit integers.
31 9     9   58 use constant SEED_SIZE => 256; # In bits
  9         27  
  9         736  
32 9     9   51 use constant SEED_MIN => 64;
  9         20  
  9         537  
33 9     9   57 use constant SEED_MAX => 8192;
  9         12  
  9         617  
34 9     9   53 use constant PRNG => 'ISAAC';
  9         23  
  9         783  
35              
36              
37 9         2090 use constant OO_ATTRIBS => {
38             Weak => 0, # Boolean. (0) Crypt::Random::Seed
39             NonBlocking => 0, # Boolean. (0) Crypt::Random::Seed
40             Only => undef, # Aref of strings. Crypt::Random::Seed
41             Never => undef, # Aref of strings. Crypt::Random::Seed
42             Source => undef, # Subref or ARef. Crypt::Random::Seed
43             PRNG => PRNG, # String. Alt RNG. Internal (ISAAC)
44             Bits => SEED_SIZE, # Seed 64 <= Bits <= 8192. Internal (256)
45 9     9   51 };
  9         19  
46              
47             # Function interface seed attributes (standard, and lite).
48 9         894 use constant FUNC_STD => {
49             Weak => 0,
50             NonBlocking => 0,
51             Bits => SEED_SIZE,
52 9     9   56 };
  9         13  
53              
54              
55 9         24376 use constant CRYPT_RANDOM_SEED_OPTS =>
56 9     9   58 [ qw( Weak NonBlocking Only Never Source ) ];
  9         16  
57              
58              
59              
60             ################################################################################
61             # OO interface class/object methods: ##
62             ################################################################################
63              
64             # Constructor
65             sub new {
66 8     8 1 13782 my ( $class, @config ) = @_;
67              
68 8         24 my $self = bless {}, $class;
69 8         43 my $args_href = $self->_build_args(@config);
70 8         34 $self->_build_attributes($args_href);
71              
72 8         34 return $self;
73             }
74              
75              
76             sub _build_args {
77 13     13   4881 my ( $self, @args ) = @_;
78              
79 13 100       58 @args = %{ $args[0] } if ref $args[0] eq 'HASH';
  3         18  
80              
81 13 100       282 croak "Illegal argument list; key => value pairs expected."
82             if @args % 2;
83              
84 12         46 my %args = $self->_validate_args( OO_ATTRIBS, @args );
85              
86 12 100       44 if ( exists $args{Bits} ) {
87 7         38 $args{Bits} = $self->_round_bits_to_ge_32( $args{Bits} );
88 7         30 $args{Bits} = $self->_constrain_bits( $args{Bits}, SEED_MIN, SEED_MAX );
89             }
90              
91 12         38 return \%args;
92             }
93              
94              
95             # _build_args() helpers:
96              
97             # Verify drop illegal or 'undef' args.
98             sub _validate_args {
99 13     13   593 my( $self, $legal_args_href, %args ) = @_;
100              
101             # Iterate through input args.
102 13         209 while( my ( $arg_key, $arg_value ) = each %args ) {
103              
104             # Disqualify if not in white list.
105 25 50       64 if( ! exists $legal_args_href->{$arg_key} ) {
106 0         0 carp "Illegal argument ($arg_key) will be ignored.";
107 0         0 delete $args{$arg_key};
108 0         0 next;
109             }
110              
111             # Disqualify if undef passed.
112 25 50       111 if( ! defined $arg_value ) {
113 0         0 carp "Undefined value specified for attribute ($arg_key). "
114             . "Attribute will be ignored.";
115 0         0 delete $args{$arg_key};
116             }
117             }
118 13         60 return %args;
119             }
120              
121              
122             # Round bits parameter to nearest greater or equal 32-bit "long".
123             sub _round_bits_to_ge_32 {
124 10     10   2459 my( $self, $bits ) = @_;
125 10         23 my $remainder = $bits % 32;
126 10 50       48 return $bits if $remainder == 0;
127 0         0 carp "Bits field must be a multiple of 32. Rounding up.";
128 0         0 return $bits + 32 - $remainder;
129             }
130              
131              
132             # Constrain bits argument to a reasonable range.
133             sub _constrain_bits {
134 8     8   992 my( $self, $bits, $min, $max ) = @_;
135              
136 8 50       49 if( $bits < $min ) {
    50          
137 0         0 carp "Bits field must be >= 64 (two longs). Rounding up.";
138 0         0 $bits = $min;
139             }
140             elsif( $bits > $max ) {
141 0         0 carp "Bits field must be <= 8192 (256 longs). Rounding down.";
142 0         0 $bits = $max;
143             }
144             # No need for an 'else' here.
145            
146 8         22 return $bits;
147             }
148              
149              
150             # Build attributes set by new(). Any not explicitly set will use defaults
151             # as described in the constant OO_ATTRIBS.
152             sub _build_attributes {
153 8     8   17 my ( $self, $args ) = @_;
154              
155 8         17 while ( my ( $arg, $default ) = each %{ OO_ATTRIBS() } ) {
  64         167  
156 56 100       193 $self->{$arg} = exists $args->{$arg} ? $args->{$arg} : $default;
157             }
158              
159 8         178 $self->{_RNG} = undef; # Lazy initialization.
160 8         25 return $self;
161             }
162              
163              
164             # Get a seed and use it to instantiate a RNG.
165             # Note: Currently we specify only Math::Random::ISAAC. However, the PRNG
166             # object attribute may be used in the future to specify alternate RNG's.
167             sub _instantiate_rng {
168 8     8   1248 my $self = shift;
169              
170 8         39 my ( %seed_opts ) = $self->_build_seed_options;
171 8         44 my @seeds = $self->_generate_seed( %seed_opts );
172 8         927 $self->{_RNG} = Math::Random::ISAAC->new(@seeds);
173              
174 8         230 return $self->{_RNG};
175             }
176              
177              
178             # Set up seed options for Crypt::Random::Seed
179             sub _build_seed_options {
180 9     9   21 my( $self ) = @_;
181              
182 9         15 my %crs_opts;
183              
184             # CRYPT_RANDOM_SEED_OPTS enumerates the options that Crypt::Random::Seed
185             # supports. We have already built object attributes for those options.
186 9         16 foreach my $opt ( @{ CRYPT_RANDOM_SEED_OPTS() } ) {
  9         33  
187 45 100       148 $crs_opts{$opt} = $self->{$opt} if defined $self->{$opt};
188             }
189              
190 9         67 return %crs_opts;
191             }
192              
193              
194             # Use Crypt::Random::Seed to generate some high-quality long int
195             # seeds for Math::Random::ISAAC.
196             sub _generate_seed {
197 10     10   491 my ( $self, %options_hash ) = @_;
198              
199 10         33 my $seed_size = $self->{Bits} / 32;
200 10         105 my $source = Crypt::Random::Seed->new(%options_hash);
201              
202 10 100       10057 croak 'Unable to obtain a strong seed source from Crypt::Random::Seed.'
203             unless defined $source;
204              
205 9         46 return $source->random_values($seed_size); # List of unsigned longs.
206             }
207              
208              
209             # Validate that we are getting an integer >= 0.
210             # If not, throw an exception.
211             sub _validate_int {
212 2718     2718   11872 my( $self, $input ) = @_;
213 2718 100 100     14897 croak "Byte count must be a positive integer."
      100        
214             unless looks_like_number( $input )
215             && $input == int( $input )
216             && $input >= 0;
217 2710         2296 return 1;
218             }
219              
220              
221             # Random bytes string.
222             sub bytes {
223 2562     2562 1 5314 my( $self, $bytes ) = @_;
224 2562 100       2797 $bytes = defined $bytes ? $bytes : 0; # Default to zero bytes.
225 2562         2849 $self->_validate_int( $bytes ); # Throws on violation.
226              
227 2559 100       3617 $self->_instantiate_rng unless defined $self->{_RNG};
228              
229 2559         1943 my $str = '';
230              
231 2559         3610 while ( $bytes >= 4 ) { # Utilize irand()'s 32 bits.
232 8633         25346 $str .= pack( "L", $self->{_RNG}->irand );
233 8633         67162 $bytes -= 4;
234             }
235              
236 2559 100       3234 if ( $bytes > 0 ) {
237 2528         4074 my $rval = $self->{_RNG}->irand;
238              
239 2528 100       11316 $str .= pack( "S", ( $rval >> 8 ) & 0xFFFF )
240             if $bytes >= 2; # 16 bits.
241 2528 100       5066 $str .= pack( "C", $rval & 0xFF ) if $bytes % 2; # 8 bits.
242              
243             }
244 2559         254621 return $str;
245             }
246              
247             # Base64 encoding of random byte string.
248             sub bytes_base64 {
249 2     2 1 6 my ( $self, $bytes, $eol ) = @_;
250 2 100       7 return encode_base64( $self->bytes($bytes), defined($eol) ? $eol : qq{\n} );
251             }
252              
253             # Hex digits representing random byte string (No whitespace, no '0x').
254             sub bytes_hex {
255 1     1 1 4 my ( $self, $bytes ) = @_;
256 1         4 return unpack 'H*', $self->bytes($bytes);
257             }
258              
259             # Quoted Printable representation of random byte string.
260             sub bytes_qp {
261 2     2 1 5 my ( $self, $bytes, $eol ) = @_;
262 2 100       6 return encode_qp $self->bytes($bytes), defined($eol) ? $eol : qq{\n}, 1;
263             }
264              
265              
266             sub string_from {
267 150     150 1 5264 my( $self, $bag, $bytes ) = @_;
268 150 100       282 $bag = defined $bag ? $bag : '';
269 150 100       378 $bytes = defined $bytes ? $bytes : 0;
270 150         336 my $range = length $bag;
271            
272 150         10113 $self->_validate_int( $bytes );
273            
274 149 100       474 croak "Bag's size must be at least 1 character."
275             if $range < 1;
276              
277 148         168 my $rand_bytes = q{}; # We need an empty (and defined) string.
278            
279 148         292 for my $random ( $self->_ranged_randoms( $range, $bytes ) ) {
280 427         1850 $rand_bytes .= substr( $bag, $random, 1 );
281             }
282              
283 148         869 return $rand_bytes;
284             }
285              
286              
287             sub shuffle {
288 2     2 1 5835 my($self, $aref) = @_;
289 2 100       272 croak 'Argument must be an array reference.' unless 'ARRAY' eq ref $aref;
290 1 50       6 return $aref unless @$aref;
291 1         6 for (my $i = @$aref; --$i;) {
292 15         39 my $r = ($self->_ranged_randoms($i+1, 1))[0];
293 15         49 ($aref->[$i],$aref->[$r]) = ($aref->[$r], $aref->[$i]);
294             }
295 1         4 return $aref;
296             }
297              
298             # Helpers for string_from() and shuffle.
299              
300             sub _ranged_randoms {
301 10198     10198   37391 my ( $self, $range, $count ) = @_;
302 10198 100       14907 $count = defined $count ? $count : 0;
303              
304             # Lazily seed the RNG so we don't waste available strong entropy.
305 10198 100       19397 $self->_instantiate_rng unless defined $self->{_RNG};
306              
307 10198         15060 my $divisor = $self->_closest_divisor($range);
308              
309 10198         10714 my @randoms;
310            
311 10198         20343 $#randoms = $count - 1; # Pre-extend the @randoms array so 'push' avoids
312             # copy on resize.
313 10198         13122 @randoms = (); # Then purge it, but its memory won't be released.
314              
315 10198         16629 for my $n ( 1 .. $count ) {
316 10530         9059 my $random;
317              
318             # The loop rolls, and re-rolls if the random number is out of the bag's
319             # range. This is to avoid a solution that would introduce modulo bias.
320 10530         8602 do {
321 10633         27175 $random = $self->{_RNG}->irand % $divisor;
322             } while ( $random >= $range );
323              
324 10530         78875 push @randoms, $random;
325             }
326              
327 10198         33617 return @randoms;
328             }
329              
330              
331             # Find nearest factor of 2**32 >= $range.
332              
333             sub _closest_divisor {
334 10229     10229   23046 my ( $self, $range ) = @_;
335 10229 100       13874 $range = defined $range ? $range : 0;
336              
337 10229 100       17101 croak "$range must be positive." if $range < 0;
338 10228 100       16046 croak "$range exceeds irand max limit of 2**32." if $range > 2**32;
339              
340 10227         9155 my $n = 0;
341 10227         8380 my $d;
342 10227         16615 while ( $n <= 32 ) {
343 51384         45963 $d = 2 ** $n++;
344 51384 100       112114 last if $d >= $range;
345             }
346            
347 10227         16540 return $d;
348             }
349              
350              
351              
352             # irand, so that people who don't need "bytes" can enjoy B::R::S's convenience
353             # without jumping through "unpack" hoops. (A suggestion from Dana Jacobsen.)
354              
355             sub irand {
356 10002     10002 1 115013 my( $self ) = @_;
357 10002 100       21639 $self->_instantiate_rng unless defined $self->{_RNG};
358 10002         23127 return $self->{_RNG}->irand;
359             }
360              
361              
362             ################################################################################
363             ## Functions interface ##
364             ################################################################################
365              
366             # Instantiate our random number generator(s) inside of a lexical closure,
367             # limiting the scope of the RNG object so it can't be tampered with.
368              
369             {
370             my $RNG_object = undef;
371              
372              
373             # Lazily, instantiate the RNG object, but only once.
374             my $fetch_RNG = sub {
375             $RNG_object = Bytes::Random::Secure->new( FUNC_STD )
376             unless defined $RNG_object;
377             return $RNG_object;
378             };
379              
380              
381             sub random_bytes {
382 55     55 1 13788 return $fetch_RNG->()->bytes( @_ );
383             }
384              
385              
386             sub random_string_from {
387 62     62 1 2314 return $fetch_RNG->()->string_from( @_ );
388             }
389              
390             }
391              
392              
393             # Base64 encoded random bytes functions
394              
395             sub random_bytes_base64 {
396 6     6 1 15 my ( $bytes, $eof ) = @_;
397 6 100       152 return encode_base64 random_bytes($bytes), defined($eof) ? $eof : qq{\n};
398             }
399              
400              
401             # Hex digit encoded random bytes
402              
403             sub random_bytes_hex {
404 27     27 1 12362 return unpack 'H*', random_bytes( shift );
405             }
406              
407              
408             # Quoted Printable encoded random bytes
409              
410             sub random_bytes_qp {
411 6     6 1 13 my ( $bytes, $eof ) = @_;
412 6 100       13 return encode_qp random_bytes($bytes), defined($eof) ? $eof : qq{\n}, 1;
413             }
414              
415              
416             1;
417              
418             =pod
419              
420             =head1 NAME
421              
422             Bytes::Random::Secure - Perl extension to generate cryptographically-secure
423             random bytes.
424              
425             =head1 SYNOPSIS
426              
427              
428             use Bytes::Random::Secure qw(
429             random_bytes random_bytes_base64 random_bytes_hex
430             );
431              
432             my $bytes = random_bytes(32); # A string of 32 random bytes.
433              
434             my $bytes = random_string_from( 'abcde', 10 ); # 10 random a,b,c,d, and e's.
435              
436             my $bytes_as_base64 = random_bytes_base64(57); # Base64 encoded rand bytes.
437              
438             my $bytes_as_hex = random_bytes_hex(8); # Eight random bytes as hex digits.
439              
440             my $bytes_as_quoted_printable = random_bytes_qp(100); # QP encoded bytes.
441              
442              
443             my $random = Bytes::Random::Secure->new(
444             Bits => 64,
445             NonBlocking => 1,
446             ); # Seed with 64 bits, and use /dev/urandom (or other non-blocking).
447              
448             my $bytes = $random->bytes(32); # A string of 32 random bytes.
449             my $long = $random->irand; # 32-bit random integer.
450              
451              
452             =head1 DESCRIPTION
453              
454             L provides two interfaces for obtaining crypto-quality
455             random bytes. The simple interface is built around plain functions. For
456             greater control over the Random Number Generator's seeding, there is an Object
457             Oriented interface that provides much more flexibility.
458              
459             The "functions" interface provides functions that can be used any time you need
460             a string of a specific number of random bytes. The random bytes are available
461             as simple strings, or as hex-digits, Quoted Printable, or MIME Base64. There
462             are equivalent methods available from the OO interface, plus a few others.
463              
464             This module can be a drop-in replacement for L, with the primary
465             enhancement of using a cryptographic-quality random number generator to create
466             the random data. The C function emulates the user interface of
467             L's function by the same name. But with Bytes::Random::Secure
468             the random number generator comes from L, and is suitable
469             for cryptographic purposes. The harder problem to solve is how to seed the
470             generator. This module uses L to generate the initial
471             seeds for Math::Random::ISAAC.
472              
473             In addition to providing C, this module also provides several
474             functions not found in L: C,
475             C, C, and C.
476              
477             And finally, for those who need finer control over how L
478             generates its seed, there is an object oriented interface with a constructor
479             that facilitates configuring the seeding process, while providing methods that
480             do everything the "functions" interface can do (truth be told, the functions
481             interface is just a thin wrapper around the OO version, with some sane defaults
482             selected). The OO interface also provides an C method, not available
483             through the functions interface.
484              
485             =head1 RATIONALE
486              
487             There are many uses for cryptographic quality randomness. This module aims to
488             provide a generalized tool that can fit into many applications while providing
489             a minimal dependency chain, and a user interface that is simple. You're free
490             to come up with your own use-cases, but there are several obvious ones:
491              
492             =over 4
493              
494             =item * Creating temporary passphrases (C).
495              
496             =item * Generating per-account random salt to be hashed along with passphrases
497             (and stored alongside them) to prevent rainbow table attacks.
498              
499             =item * Generating a secret that can be hashed along with a cookie's session
500             content to prevent cookie forgeries.
501              
502             =item * Building raw cryptographic-quality pseudo-random data sets for testing
503             or sampling.
504              
505             =item * Feeding secure key-gen utilities.
506              
507             =back
508              
509             Why use this module? This module employs several well-designed CPAN tools to
510             first generate a strong random seed, and then to instantiate a high quality
511             random number generator based on the seed. The code in this module really
512             just glues together the building blocks. However, it has taken a good deal of
513             research to come up with what I feel is a strong tool-chain that isn't going to
514             fall back to a weak state on some systems. The interface is designed with
515             simplicity in mind, to minimize the potential for misconfiguration.
516              
517             =head1 EXPORTS
518              
519             By default C is the only function exported. Optionally
520             C, C, C,
521             and C may be exported.
522              
523             =head1 FUNCTIONS
524              
525             The B seeds the ISAAC generator on first use with a 256 bit
526             seed that uses Crypt::Random::Seed's default configuration as a strong random
527             seed source.
528              
529             =head2 random_bytes
530              
531             my $random_bytes = random_bytes( 512 );
532            
533             Returns a string containing as many random bytes as requested. Obviously the
534             string isn't useful for display, as it can contain any byte value from 0 through
535             255.
536              
537             The parameter is a byte-count, and must be an integer greater or equal to zero.
538              
539             =head2 random_string_from
540              
541             my $random_bytes = random_string_from( $bag, $length );
542             my $random_bytes = random_string_from( 'abc', 50 );
543              
544             C<$bag> is a string of characters from which C may choose in
545             building a random string. We call it a 'bag', because it's permissible to have
546             repeated chars in the bag (if not, we could call it a set). Repeated digits
547             get more weight. For example, C would have a
548             66.67% chance of returning an 'a', and a 33.33% chance of returning a 'b'. For
549             unweighted distribution, ensure there are no duplicates in C<$bag>.
550              
551             This I a "draw and discard", or a permutation algorithm; each character
552             selected is independent of previous or subsequent selections; duplicate
553             selections are possible by design.
554              
555             Return value is a string of size C<$length>, of characters chosen at random
556             from the 'bag' string.
557              
558             It is perfectly legal to pass a Unicode string as the "bag", and in that case,
559             the yield will include Unicode characters selected from those passed in via the
560             bag string.
561              
562             This function is useful for random string generation such as temporary
563             random passwords.
564              
565             =head2 random_bytes_base64
566              
567             my $random_bytes_b64 = random_bytes_base64( $num_bytes );
568             my $random_bytes_b64_formatted = random_bytes_base64( $num_bytes, $eol );
569              
570             Returns a MIME Base64 encoding of a string of $number_of_bytes random bytes.
571             Note, it should be obvious, but is worth mentioning that a base64 encoding of
572             base256 data requires more digits to represent the bytes requested. The actual
573             number of digits required, including padding is C<4(n/3)>.
574             Furthermore, the Base64 standard is to add padding to the end of any string for
575             which C is a non-zero value.
576              
577             If an C<$eol> is specified, the character(s) specified will be used as line
578             delimiters after every 76th character. The default is C. If you wish
579             to eliminate line-break insertions, specify an empty string: C.
580              
581             =head2 random_bytes_hex
582              
583             my $random_bytes_as_hex = random_bytes_hex( $num_bytes );
584              
585             Returns a string of hex digits representing the string of $number_of_bytes
586             random bytes.
587              
588             It's worth mentioning that a hex (base16) representation of base256 data
589             requires two digits for every byte requested. So
590             C will return 32, as it takes 32 hex digits to
591             represent 16 bytes. Simple stuff, but better to mention it now than forget and
592             set a database field that's too narrow.
593              
594             =head2 random_bytes_qp
595              
596             my $random_bytes_qp = random_bytes_qp( $num_bytes );
597             my $random_bytes_qp_formatted = random_bytes_qp( $num_bytes, $eol );
598              
599             Produces a string of C<$num_bytes> random bytes, using MIME Quoted Printable
600             encoding (as produced by L's C function. The
601             default configuration uses C<\n> as a line break after every 76 characters, and
602             the "binmode" setting is used to guarantee a lossless round trip. If no line
603             break is wanted, pass an empty string as C<$eol>.
604              
605             =head1 METHODS
606              
607             The B provides methods that mirror the "functions"
608             interface. However, the OO interface offers the advantage that the user can
609             control how many bits of entropy are used in seeding, and even how
610             L is configured.
611              
612             =head2 new
613              
614             my $random = Bytes::Random::Secure->new( Bits => 512 );
615             my $bytes = $random->bytes( 32 );
616              
617             The constructor is used to specify how the ISAAC generator is seeded. Future
618             versions may also allow for alternate CSPRNGs to be selected. If no parameters
619             are passed the default configuration specifies 256 bits for the seed. The rest
620             of the default configuration accepts the L defaults, which
621             favor the strongest operating system provided entropy source, which in many
622             cases may be "blocking".
623              
624             =head3 CONSTRUCTOR PARAMETERS
625              
626             =head4 Bits
627              
628             my $random = Bytes::Random::Secure->new( Bits => 128 );
629            
630             The C parameter specifies how many bits (rounded up to nearest multiple of
631             32) will be used in seeding the ISAAC random number generator. The default is
632             256 bits of entropy. But in some cases it may not be necessary, or even wise to
633             pull so many bits of entropy out of C (a blocking source).
634              
635             Any value between 64 and 8192 will be accepted. If an out-of-range value is
636             specified, or a value that is not a multiple of 32, a warning will be generated
637             and the parameter will be rounded up to the nearest multiple of 32 within the
638             range of 64 through 8192 bits. So if 16384 is specified, you will get 8192. If
639             33 is specified, you will get 64.
640              
641             B In the Perlish spirit of "I", the maximum number
642             of bits this module accepts is 8192, which is the maximum number that ISAAC can
643             utilize. But just because you I specify a seed of 8192 bits doesn't mean
644             you ought to, much less need to. And if you do, you probably want to use the
645             C option, discussed below. 8192 bits is a lot to ask from a
646             blocking source such as C, and really anything beyond 512 bits in
647             the seed is probably wasteful.
648              
649              
650             =head4 PRNG
651              
652             Reserved for future use. Eventually the user will be able to select other RNGs
653             aside from Math::Random::ISAAC.
654              
655             =head4 Unique
656              
657             Reserved for future use.
658              
659             =head4 Other Crypt::Random::Seed Configuration Parameters
660              
661             For additional seeding control, refer to the POD for L.
662             By supplying a Crypt::Random::Seed parameter to Bytes::Random::Secure's
663             constructor, it will be passed through to Crypt::Random::Seed. For example:
664              
665             my $random = Bytes::Random::Secure->new( NonBlocking => 1, Bits => 64 );
666              
667             In this example, C is used internally, while C is passed
668             through to Crypt::Random::Seed.
669              
670              
671             =head2 bytes
672              
673             my $random_bytes = $random->bytes(1024);
674              
675             This works just like the C function.
676              
677              
678             =head2 string_from
679              
680             my $random_string = $random->string_from( 'abcdefg', 10 );
681              
682             Just like C: Returns a string of random octets selected
683             from the "Bag" string (in this case ten octets from 'abcdefg').
684              
685              
686             =head2 bytes_hex
687              
688             my $random_hex = $random->bytes_hex(12);
689              
690             Identical in function to C.
691              
692              
693             =head2 bytes_base64
694              
695             my $random_base64 = $random->bytes_base64( 32, EOL => "\n" );
696              
697             Identical in function to C.
698              
699              
700             =head2 bytes_qp
701              
702             my $random_qp = $random->bytes_qp( 80 );
703              
704             You guessed it: Identical in function to C.
705              
706              
707             =head2 irand
708              
709             my $unsigned_long = $random->irand;
710              
711             Returns a random 32-bit unsigned integer. The value will satisfy
712             C<< 0 <= x <= 2**32-1 >>. This functionality is only available through the OO
713             interface.
714              
715             =head2 shuffle
716              
717             my $aref_shuffled = $random->shuffle($aref);
718              
719             Shuffles the contents of a reference to an array in sitiu, and returns
720             the same reference.
721              
722             L, which ships with Perl, includes C function. But that
723             function is flawed in two ways. First, from a cryptographic standpoint,
724             it uses Perl's C, which is not a CSPRNG, and therefore is inadequate.
725              
726             Second, because Perl's rand has an internal state of just 32 bits, it cannot
727             possibly generate all permutations of arrays containing 13 or more elements.
728              
729             This module's C uses a CSPRNG, and also benefits from large seeds
730             and a huge internal state. ISAAC can be seeded with up to 8192 bits, yielding
731             2^8192 possible initial states, and 2^8288 possible internal states. A seed of
732             8192 bits will assure that for arrays of up to 966 elements every permutation
733             is accessible.
734              
735             =head1 CONFIGURATION
736              
737             L's interface tries to I. There is
738             generally nothing to configure. This design, eliminates much of the potential
739             for diminishing the quality of the random byte stream through misconfiguration.
740             The ISAAC algorithm is used as our factory, seeded with a strong source.
741              
742             There may be times when the default seed characteristics carry too heavy a
743             burden on system resources. The default seed for the functions interface is
744             256 bits of entropy taken from /dev/random (a blocking source on many systems),
745             or via API calls on Windows. The default seed size for the OO interface is also
746             256 bits. If /dev/random should become depleted at the time that this module
747             attempts to seed the ISAAC generator, there could be delay while additional
748             system entropy is generated. If this is a problem, it is possible to override
749             the default seeding characteristics using the OO interface instead of the
750             functions interface. However, under most circumstances, this capability may be
751             safely ignored.
752              
753             Beginning with Bytes::Random::Secure version 0.20, L
754             provides our strong seed (previously it was Crypt::Random::Source). This module
755             gives us excellent "strong source" failsafe behavior, while keeping the
756             non-core dependencies to a bare minimum. Best of all, it performs well across
757             a wide variety of platforms, and is compatible with Perl versions back through
758             5.6.0.
759              
760             And as mentioned earlier in this document, there may be circumstances where
761             the performance of the operating system's strong random source is prohibitive
762             from using the module's default seeding configuration. Use the OO interface
763             instead, and read the documentation for L to learn what
764             options are available.
765              
766             Prior to version 0.20, a heavy dependency chain was required for reliably
767             and securely seeding the ISAAC generator. Earlier versions required
768             L, which in turn required L. Thanks to Dana
769             Jacobsen's new Crypt::Random::Seed module, this situation has been resolved.
770             So if you're looking for a secure random bytes solution that "just works"
771             portably, and on Perl versions as far back as 5.6.0, you've come to the right
772             place. Users of older versions of this module are encouraged to update to
773             version 0.20 or higher to benefit from the improved user interface and lighter
774             dependency chain.
775              
776              
777             =head2 OPTIONAL (RECOMMENDED) DEPENDENCY
778              
779             If performance is a consideration, you may also install
780             L. Bytes::Random::Secure's random number generator
781             uses L. That module implements the ISAAC algorithm in pure
782             Perl. However, if you install L, you
783             get the same algorithm implemented in C/XS, which will provide better
784             performance. If you need to produce your random bytes more quickly, simply
785             installing Math::Random::ISAAC::XS will result in it automatically being used,
786             and a pretty good performance improvement will coincide.
787              
788              
789             =head1 CAVEATS
790              
791             =head2 FORK AND THREAD SAFETY
792              
793             When programming for parallel computation, avoid the "functions" interface B
794             use the Object Oriented interface, and create a unique C
795             object within each process or thread. Bytes::Random::Secure uses
796             a CSPRNG, and sharing the same RNG between threads or processes will share the
797             same seed and the same starting point. This is probably not what one would
798             want to do. By instantiating the B::R::S object after forking or creating
799             threads, a unique randomness stream will be created per thread or process.
800              
801             =head2 STRONG RANDOMNESS
802              
803             It's easy to generate weak pseudo-random bytes. It's also easy to think you're
804             generating strong pseudo-random bytes when really you're not. And it's hard to
805             test for pseudo-random cryptographic acceptable quality. There are many high
806             quality random number generators that are suitable for statistical purposes,
807             but not necessarily up to the rigors of cryptographic use.
808              
809             Assuring strong (ie, secure) random bytes in a way that works across a wide
810             variety of platforms is also challenging. A primary goal for this module is to
811             provide cryptographically secure pseudo-random bytes. A secondary goal is to
812             provide a simple user experience (thus reducing the propensity for getting it
813             wrong). A tertiary goal is to minimize the dependencies required to achieve
814             the primary and secondary goals, to the extent that is practical.
815              
816             =head2 ISAAC
817              
818             The ISAAC algorithm is considered to be a cryptographically strong pseudo-random
819             number generator. There are 1.0e2466 initial states. The best known attack for
820             discovering initial state would theoretically take a complexity of
821             approximately 4.67e1240, which has no practical impact on ISAAC's security.
822             Cycles are guaranteed to have a minimum length of 2**40, with an average cycle
823             of 2**8295. Because there is no practical attack capable of discovering
824             initial state, and because the average cycle is so long, it's generally
825             unnecessary to re-seed a running application. The results are uniformly
826             distributed, unbiased, and unpredictable unless the seed is known.
827              
828             To confirm the quality of the CSPRNG, this module's test suite implements the
829             L tests for
830             strong random number generators. See the comments in C for
831             details.
832              
833             =head2 DEPENDENCIES
834              
835             To keep the dependencies as light as possible this module uses some ideas from
836             L. That module is an excellent resource, but implements
837             a broader range of functionality than is needed here. So we just borrowed
838             from it.
839              
840             The primary source of random data in this module comes from the excellent
841             L. To be useful and secure, even Math::Random::ISAAC
842             needs a cryptographically sound seed, which we derive from
843             L. There are no known weaknesses in the ISAAC algorithm.
844             And Crypt::Random::Seed does a very good job of preventing fall-back to weak
845             seed sources.
846              
847             This module requires Perl 5.6 or newer. The module also uses a number of core
848             modules, some of which require newer versions than those contemporary with 5.6.
849             Unicode support in C is best with Perl 5.8.9 or newer.
850             See the INSTALLATION section in this document for details.
851              
852             If L is installed, test coverage is 100%. For those who don't want
853             to bother installing Test::Warn, you can just take our word for it. It's an
854             optional installation dependency.
855              
856             =head2 BLOCKING ENTROPY SOURCE
857              
858             It is possible (and has been seen in testing) that the system's random
859             entropy source might not have enough entropy in reserve to generate the seed
860             requested by this module without blocking. If you suspect that you're a victim
861             of blocking from reads on C, one option is to manipulate the
862             random seed configuration by using the object oriented interface.
863              
864             This module seeds as lazily as possible so that using the module, and even
865             instantiating a Bytes::Random::Secure object will not trigger reads from
866             C. Only the first time the object is used to deliver random bytes
867             will the RNG be seeded. Long-running scripts may prefer to force early seeding
868             as close to start-up time as possible, rather than allowing it to happen later
869             in a program's run-time. This can be achieved simply by invoking any of the
870             functions or methods that return a random byte. As soon as a random byte is
871             requested for the first time, the CSPRNG will be seeded.
872              
873             =head2 UNICODE SUPPORT
874              
875             The C function, and C method permit the user
876             to pass a "bag" (or source) string containing Unicode characters. For any
877             modern Perl version, this will work just as you would hope. But some versions
878             of Perl older than 5.8.9 exhibited varying degrees of bugginess in their
879             handling of Unicode. If you're depending on the Unicode features of this
880             module while using Perl versions older than 5.8.9 be sure to test thoroughly,
881             and don't be surprised when the outcome isn't as expected. ...this is to be
882             expected. Upgrade.
883              
884             No other functions or methods in this module get anywhere near Perl's Unicode
885             features. So as long as you're not passing Unicode source strings to
886             C, you have nothing to worry about, even if you're using
887             Perl 5.6.0.
888              
889             =head2 MODULO BIAS
890              
891             Care is taken so that there is no modulo bias in the randomness returned
892             either by C or its siblings, nor by C. As a
893             matter if fact, this is exactly I the C function is
894             useful. However, the algorithm to eliminate modulo bias can impact the
895             performance of the C function. Any time the length of the
896             bag string is significantly less than the nearest greater or equal factor
897             of 2**32, performance will degrade. Unfortunately there is no known algorithm
898             that improves upon this situation. Fortunately, for sanely sized strings, it's
899             a minor issue. To put it in perspective, even in the case of passing a "bag"
900             string of length 2**31 (which is huge), the expected time to return random
901             bytes will only double. Given that the entire Unicode range is just over a
902             million possible code-points, it seems unlikely that the normal use case would
903             ever have to be concerned with the performance of the C
904             function.
905              
906             =head1 INSTALLATION
907              
908             This module should install without any fuss on modern versions of Perl. For
909             older Perl versions (particularly 5.6 and early 5.8.x's), it may be necessary
910             to update your CPAN installer to a more modern version before installing this
911             this module.
912              
913             Another alternative for those with old Perl versions who don't want to update
914             their CPAN installer (You must know you're crazy, right?): Review C
915             and assure that you've got the dependencies listed under C and
916             C, in at least the minimum versions specified. Then proceed as
917             usual.
918              
919             This module only has two non-Core dependencies. But it does expect that some
920             of the Core dependencies are newer than those supplied with 5.6 or early 5.8's.
921             If you keep your CPAN installer up-to-date, you shouldn't have to think about
922             this, as it will usually just "do the right thing", pulling in newer dependency
923             versions as directed by the module's META files.
924              
925             Test coverage for Bytes::Random::Secure is 100% (per Devel::Cover) on any
926             system that has L installed. But to keep the module light-weight,
927             Test::Warn is not dragged in by default at installation time.
928              
929             =head1 SEE ALSO
930              
931             L and L provide strong CSPRINGs and even
932             more configuration options, but come with hefty toolchains.
933              
934             L is a stand-alone adaptation of
935             L with no dependencies. It will, however, detect if
936             L, L, and L
937             are installed on the target system, and if they are, it quietly upgrades to
938             using them.
939              
940             =head1 AUTHOR
941              
942             David Oswald C<< >>
943              
944             =head1 BUGS
945              
946             Please report any bugs or feature requests to
947             C, or through the web interface at
948             L. I will
949             be notified, and then you'll automatically be notified of progress on your bug
950             as I make changes.
951              
952             =head1 SUPPORT
953              
954             You can find documentation for this module with the perldoc command.
955              
956             perldoc Bytes::Random::Secure
957              
958              
959             You can also look for information at:
960              
961             =over 4
962              
963             =item * Github Repo: L
964              
965             =item * RT: CPAN's request tracker (report bugs here)
966              
967             L
968              
969             =item * AnnoCPAN: Annotated CPAN documentation
970              
971             L
972              
973             =item * CPAN Ratings
974              
975             L
976              
977             =item * Search CPAN
978              
979             L
980              
981             =back
982              
983              
984             =head1 ACKNOWLEDGEMENTS
985              
986             Dana Jacobsen ( I<< >> ) for his work that led to
987             L, thereby significantly reducing the dependencies while
988             improving the portability and backward compatibility of this module. Also for
989             providing a patch to this module that greatly improved the performance
990             of C.
991              
992             Dana Jacosen also provided extensive input, code reviews, and testing that
993             helped to guide the direction this module has taken. The code for the
994             FIPS-140-1 tests was taken directly from L. Thanks!
995              
996             L for implementing a nice, simple interface that this module
997             patterns itself after.
998              
999             =head1 LICENSE AND COPYRIGHT
1000              
1001             Copyright 2012 David Oswald.
1002              
1003             This program is free software; you can redistribute it and/or modify it
1004             under the terms of either: the GNU General Public License as published
1005             by the Free Software Foundation; or the Artistic License.
1006              
1007             See http://dev.perl.org/licenses/ for more information.
1008              
1009             =cut