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