File Coverage

blib/lib/Bytes/Random/Secure.pm
Criterion Covered Total %
statement 174 174 100.0
branch 62 62 100.0
condition 6 6 100.0
subroutine 40 40 100.0
pod 12 12 100.0
total 294 294 100.0


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