File Coverage

blib/lib/Crypt/PRNG.pm
Criterion Covered Total %
statement 46 47 97.8
branch 13 16 81.2
condition n/a
subroutine 14 15 93.3
pod 10 10 100.0
total 83 88 94.3


line stmt bran cond sub pod time code
1             package Crypt::PRNG;
2              
3 28     28   101761 use strict;
  28         54  
  28         1055  
4 28     28   138 use warnings;
  28         47  
  28         4632  
5             our $VERSION = '0.089';
6              
7             require Exporter; our @ISA = qw(Exporter); ### use Exporter 5.57 'import';
8             our %EXPORT_TAGS = ( all => [qw(random_bytes random_bytes_hex random_bytes_b64 random_bytes_b64u random_string random_string_from rand irand)] );
9             our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
10             our @EXPORT = qw();
11              
12 28     28   186 use Carp;
  28         81  
  28         2513  
13             $Carp::Internal{(__PACKAGE__)}++;
14 28     28   3242 use CryptX;
  28         68  
  28         20807  
15              
16             sub string {
17 12     12 1 2136 my ($self, $len) = @_;
18 12         54 return $self->string_from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", $len);
19             }
20              
21             sub string_from {
22 27     27 1 6880 my ($self, $chars, $len) = @_;
23              
24 27 50       76 $len = 20 unless defined $len;
25 27 50       67 return unless $len > 0;
26 27 50       77 return unless length($chars) > 0;
27              
28 27         28562 my @ch = split(//, $chars);
29 27         61 my $max_index = $#ch;
30 27 100       5902 return if $max_index > 65535;
31              
32 26         54 my $mask;
33 26         69 for my $n (1..31) {
34 126         176 $mask = (1<<$n) - 1;
35 126 100       254 last if $mask >= $max_index;
36             }
37              
38 26 100       72 my $upck = ($max_index > 255) ? "n*" : "C*";
39 26         48 my $l = $len * 2;
40              
41 26         39 my $rv = '';
42 26         40 my @r;
43 26         47 my $ri = 0;
44 26         81 while (length $rv < $len) {
45 2315 100       4090 if ($ri >= @r) {
46 26         2301 @r = unpack($upck, $self->bytes($l));
47 26         82 $ri = 0;
48             }
49 2315         3528 my $i = $r[$ri++] & $mask;
50 2315 100       4089 next if $i > $max_index;
51 2112         4391 $rv .= $ch[$i];
52             }
53 26         7020 return $rv;
54             }
55              
56 0     0   0 sub CLONE_SKIP { 1 } # prevent cloning
57              
58             ### FUNCTIONS
59              
60             {
61             ### stolen from Bytes::Random::Secure
62             #
63             # Instantiate our random number generator(s) inside of a lexical closure,
64             # limiting the scope of the RNG object so it can't be tampered with.
65             my $RNG_object = undef;
66             my $fetch_RNG = sub { # Lazily, instantiate the RNG object, but only once.
67             $RNG_object = Crypt::PRNG->new unless defined $RNG_object && ref($RNG_object) ne 'SCALAR';
68             return $RNG_object;
69             };
70 2000     2000 1 231348 sub rand(;$) { return $fetch_RNG->()->double(@_) }
71 1000     1000 1 2474 sub irand() { return $fetch_RNG->()->int32() }
72 17     17 1 24877 sub random_bytes($) { return $fetch_RNG->()->bytes(@_) }
73 4     4 1 1589 sub random_bytes_hex($) { return $fetch_RNG->()->bytes_hex(@_) }
74 4     4 1 1551 sub random_bytes_b64($) { return $fetch_RNG->()->bytes_b64(@_) }
75 4     4 1 1589 sub random_bytes_b64u($) { return $fetch_RNG->()->bytes_b64u(@_) }
76 1     1 1 5 sub random_string_from($;$) { return $fetch_RNG->()->string_from(@_) }
77 1     1 1 4 sub random_string(;$) { return $fetch_RNG->()->string(@_) }
78             }
79              
80             1;
81              
82             =pod
83              
84             =head1 NAME
85              
86             Crypt::PRNG - Cryptographically secure random number generator
87              
88             =head1 SYNOPSIS
89              
90             ### Functional interface:
91             use Crypt::PRNG qw(random_bytes random_bytes_hex random_bytes_b64 random_bytes_b64u
92             random_string random_string_from rand irand);
93              
94             my $octets = random_bytes(45);
95             my $hex_string = random_bytes_hex(45);
96             my $base64_string = random_bytes_b64(45);
97             my $base64url_string = random_bytes_b64u(45);
98             my $alphanumeric_string = random_string(30);
99             my $string = random_string_from('ACGT', 64);
100             my $floating_point_number_0_to_1 = rand;
101             my $floating_point_number_0_to_88 = rand(88);
102             my $unsigned_32bit_int = irand;
103              
104             ### OO interface:
105             use Crypt::PRNG;
106              
107             my $prng = Crypt::PRNG->new; # defaults to ChaCha20
108             my $rc4_prng = Crypt::PRNG->new("RC4");
109             my $seeded_prng = Crypt::PRNG->new("RC4", "some data used for seeding PRNG");
110              
111             my $octets = $prng->bytes(45);
112             my $hex_string = $prng->bytes_hex(45);
113             my $base64_string = $prng->bytes_b64(45);
114             my $base64url_string = $prng->bytes_b64u(45);
115             my $alphanumeric_string = $prng->string(30);
116             my $string = $prng->string_from('ACGT', 64);
117             my $floating_point_number_0_to_1 = $prng->double;
118             my $floating_point_number_0_to_88 = $prng->double(88);
119             my $unsigned_32bit_int = $prng->int32;
120              
121             =head1 DESCRIPTION
122              
123             Provides an interface to several pseudo-random number generators (thread-safe
124             and fork-safe). The default algorithm is ChaCha20.
125              
126             =head1 EXPORT
127              
128             Nothing is exported by default.
129              
130             You can export selected functions:
131              
132             use Crypt::PRNG qw(random_bytes random_string);
133              
134             Or all of them at once:
135              
136             use Crypt::PRNG ':all';
137              
138             =head1 FUNCTIONS
139              
140             For all C functions and the corresponding C methods,
141             C<$length> must not be greater than C<1000000000>.
142              
143             =head2 random_bytes
144              
145             my $octets = random_bytes($length);
146             # $length .. [integer] number of random bytes to generate
147              
148             Returns C<$length> random octets as a binary string.
149              
150             =head2 random_bytes_hex
151              
152             my $hex_string = random_bytes_hex($length);
153             # $length .. [integer] number of random bytes (output string will be 2x longer)
154              
155             Returns C<$length> random octets encoded as a lowercase hexadecimal string.
156              
157             =head2 random_bytes_b64
158              
159             my $base64_string = random_bytes_b64($length);
160             # $length .. [integer] number of random bytes to encode
161              
162             Returns C<$length> random octets encoded as a Base64 string.
163              
164             =head2 random_bytes_b64u
165              
166             my $base64url_string = random_bytes_b64u($length);
167             # $length .. [integer] number of random bytes to encode
168              
169             Returns C<$length> random octets encoded as a Base64 URL-safe string (RFC 4648 section 5).
170              
171             =head2 random_string_from
172              
173             my $string = random_string_from($range, $length);
174             # $range .. [string] alphabet of allowed characters
175             # $length .. [integer] optional, number of characters (DEFAULT: 20)
176             #e.g.
177             my $dna_string = random_string_from("ABCD", 10);
178              
179             Returns a random string of C<$length> characters chosen from C<$range>.
180             The alphabet must contain between 1 and 65536 characters; longer alphabets
181             return C.
182              
183             =head2 random_string
184              
185             my $alphanumeric_string = random_string($length);
186             # $length .. [integer] optional, number of characters (DEFAULT: 20)
187             #or
188             my $default_alphanumeric_string = random_string; # default length = 20
189              
190             Like C, but C<$range> is fixed to
191             C<'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'>.
192              
193             =head2 rand
194              
195             my $n = rand;
196             #or
197             my $limited_n = rand($limit);
198             # $limit .. [number] optional, upper bound (exclusive)
199              
200             Returns a random floating-point number in the range C<[0,1)> if called without
201             an argument, or C<[0,$limit)> if C<$limit> is given.
202             If C<$limit> is C<0>, this behaves as if no limit was given and returns a
203             value in C<[0,1)>, matching Perl's built-in C.
204              
205             =head2 irand
206              
207             my $i = irand;
208              
209             Returns a random unsigned 32-bit integer in the range C<0 .. 0xFFFFFFFF>.
210              
211             =head1 METHODS
212              
213             Unless noted otherwise, assume C<$prng> is an existing PRNG object created via
214             C, for example:
215              
216             my $prng = Crypt::PRNG->new;
217              
218             =head2 new
219              
220             my $prng = Crypt::PRNG->new; # defaults to ChaCha20
221             #or
222             my $prng = Crypt::PRNG->new($alg);
223             #or
224             my $prng = Crypt::PRNG->new($alg, $seed);
225              
226             # $alg ... [string] algorithm name: 'ChaCha20' (DEFAULT), 'Fortuna', 'RC4' (legacy; compatibility only), 'Sober128' or 'Yarrow'
227             # $seed ... [binary string] optional, initial entropy for seeding the PRNG
228              
229             If C<$seed> is not given, the PRNG is automatically seeded with 40 bytes
230             obtained via libtomcrypt's C platform RNG logic.
231              
232             If C<$seed> is specified it must be non-empty for all algorithms. RC4 is
233             provided for legacy compatibility only, is not recommended for new designs, and
234             requires a seed of at least 5 bytes.
235              
236             =head2 add_entropy
237              
238             my $prng = Crypt::PRNG->new;
239             $prng->add_entropy($random_data);
240             #or
241             $prng->add_entropy();
242              
243             If called without parameter it uses 40 bytes obtained via libtomcrypt's
244             C platform RNG logic.
245              
246             B You probably do not need this function. The module seeds itself on
247             initialization and reseeds after fork and thread creation.
248              
249             =head2 bytes
250              
251             my $octets = $prng->bytes($length);
252              
253             See L
254              
255             =head2 bytes_hex
256              
257             my $hex_string = $prng->bytes_hex($length);
258              
259             See L
260              
261             =head2 bytes_b64
262              
263             my $base64_string = $prng->bytes_b64($length);
264              
265             See L
266              
267             =head2 bytes_b64u
268              
269             my $base64url_string = $prng->bytes_b64u($length);
270              
271             See L
272              
273             =head2 string
274              
275             my $alphanumeric_string = $prng->string($length);
276             #or
277             my $default_alphanumeric_string = $prng->string; # default length = 20
278              
279             See L
280              
281             =head2 string_from
282              
283             my $string = $prng->string_from($range, $length); # default length = 20
284              
285             See L
286              
287             =head2 double
288              
289             my $n = $prng->double;
290             #or
291             my $limited_n = $prng->double($limit);
292              
293             See L
294              
295             =head2 int32
296              
297             my $i = $prng->int32;
298              
299             See L
300              
301             =head1 SEE ALSO
302              
303             L, L, L,
304             L, L
305              
306             For generating random UUIDs see L and L.
307              
308             =cut