blib/lib/Crypt/DRBG.pm

filter: Statementstmt 93.5% 131 / 140 Branchbran 80.5% 58 / 72 Conditioncond 81.4% 22 / 27 MC/DCmcdc 70.5% 12 / 17 Subroutinesub 100% 16 / 16 Podpod 100% 5 / 5 totaltotal 88.0% 244 / 277 CC 47 SCAR 20.1
CC
47
Cov
88%
_rand_bytes
19.8
_get_personalization
9.0
_check_reseed
8.1
CRAP 7.4
↑ Summary lib/Crypt/DRBG/Hash.pm »
1 package Crypt::DRBG;
2 15 $Crypt::DRBG::VERSION = '0.001000';
3 15 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 15 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 15 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 15 ▶use IO::File ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 =head1 NAME
10  
11 Crypt::DRBG - Base class for fast, cryptographically-secure PRNGs
12  
13 =head1 SYNOPSIS
14  
15 use Crypt::DRBG::HMAC;
16  
17 my $drbg = Crypt::DRBG::HMAC->new(auto => 1);
18 my $data = $drbg->generate(42);
19 ... # do something with your 42 bytes here
20  
21 my $drbg2 = Crypt::DRBG::HMAC->new(seed => "my very secret seed");
22 my @randdigits = $drbg->randitems(20, [0..9]);
23 ... # do something with your 20 random digits here
24  
25 =head1 DESCRIPTION
26  
27 Crypt::DRBG is a collection of fast, cryptographically-secure PRNGs
28 (pseudo-random number generators). It can be useful for a variety of
29 situations:
30  
31 =over 4
32  
33 =item *
34  
35 Cryptographically secure random numbers are needed in production, but for
36 testing reproducibility is needed
37  
38 =item *
39  
40 A large number of random values are needed, but using /dev/urandom (or the
41 equivalent) frequently or persistently is unsuitable
42  
43 =item *
44  
45 Selection of random values in a range (e.g. digits, letters, identifiers) is
46 required and biasing the results is unacceptable
47  
48 =back
49  
50 Crypt::DRBG::HMAC is the recommended class to use, as it's currently the
51 fastest. All algorithms are assumed to provide equivalent security.
52  
53 =head1 SUBROUTINES/METHODS
54  
55 =head2 initialize(%params)
56  
57 %params can contain the following:
58  
59 =over 4
60  
61 =item auto
62  
63 If true, use a safe, cryptographically-secure set of defaults.
64 Equivalent to specifying autoseed, autononce, autopersonalize, and
65 fork_safe.
66  
67 =item autoseed
68  
69 If true, derive a seed from Crypt::URandom, if available,
70 or from /dev/urandom, /dev/arandom, or /dev/random, in that order.
71 Windows support requires Crypt::URandom to function properly.
72  
73 =item seed
74  
75 If a string, use this value as the seed. If a coderef, call this coderef with a
76 single argument (the number of bytes) to obtain an entropy input. Note that if
77 a string is used, an exception will be thrown if a reseed is required.
78  
79 =item autononce
80  
81 If true, derive a nonce automatically.
82  
83 =item nonce
84  
85 If a string, use this value as the nonce. If a coderef, call this coderef with
86 a single argument (the number of bytes) to obtain a nonce.
87  
88 =item autopersonalize
89  
90 If true, derive a personalization string automatically.
91  
92 =item personalize
93  
94 If a string, use this value as the personalization string. If a coderef, call
95 this coderef to obtain a personalization string.
96  
97 =item fork_safe
98  
99 If true, reseed on fork. If false, the parent and child processes will produce
100 the same sequence of bytes (not recommended).
101  
102 =item cache
103  
104 If enabled, keep a cache of this many bytes and use it to satisfy requests
105 before generating more.
106  
107 =back
108  
109 =cut
110  
111 # Not a method call.
112 20 ▶sub _rand_bytes {
Subroutine _rand_bytes: called CC=6 SCAR=29.9
113 20 my ($len) = @_;
114  
115 20 my $data = eval {
116 20 require Crypt::URandom;
117 20 Crypt::URandom::urandom($len);
118 };
119  
120 20 ▶ return $data if defined $data;
Branch: 1 branch
BranchTrueFalseTotal
if defined $data 20 0 20
121  
122 0 $data = '';
123  
124 0 my @sources = qw{/dev/urandom /dev/arandom /dev/random};
125 0 foreach my $source (@sources) {
126 0 ▶ my $fh = IO::File->new($source, 'r') or next;
Branch: 1 branch
BranchTrueFalseTotal
my $fh = "IO::File"->new($source, "r") or next 0 0 0
127 0 ▶ while ($fh->read(my $buf, $len - length($data))) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fh->read(my $buf, $len - length($data))) 0 0 0
128 0 $data .= $buf;
129 }
130 0 ▶ die "Insufficient random data" if length($data) != $len;
Branch: 1 branch
BranchTrueFalseTotal
if length $data != $len 0 0 0
131 0 return $data;
132 }
133 0 die "No random source for autoseed";
134 }
135  
136 5490 ▶sub _get_seed {
Subroutine _get_seed: called CC=8 SCAR=20.8
137 5490 my ($self, $name, $len, $params, $optional) = @_;
138 5490 my $autoname = "auto$name";
139  
140 5490 my $seed;
141 5490 ▶ if (defined $params->{$name} && !ref $params->{$name}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{$name} and not ref $params->{$name}) { } 5402 88 5490
Condition100%3/3
defined $params->{$name} and not ref $params->{$name}
!ll&&!rl&&r
61275402
MC/DC100%2/2
defined $params->{$name} and not ref $params->{$name}
defined $params->{$name} not ref $params->{$name}
Truth table100%3/3
A and not(B)
A= defined $params->{$name}B= not ref $params->{$name}
ABresult
0X0
100
111
142 5402 $seed = $params->{$name};
143 }
144 else {
145 88 my $seedfunc;
146 88 ▶ $seedfunc = $params->{$name} if ref $params->{$name} eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $params->{$name} eq "CODE" 27 61 88
147 88 ▶ $seedfunc = \&_rand_bytes if $params->{$autoname} || $params->{auto};
Branch: 1 branch
BranchTrueFalseTotal
if $params->{$autoname} or $params->{"auto"} 18 70 88
Condition66%2/3
$params->{$autoname} or $params->{"auto"}
l!l&&r!l&&!r
01870
MC/DC50%1/2
$params->{$autoname} or $params->{"auto"}
$params->{$autoname} $params->{"auto"}
Truth table66%2/3
A or B
A= $params->{$autoname}B= $params->{"auto"}
ABresult
1X1
011
000
148 88 ▶ unless ($seedfunc) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($seedfunc) 43 45 88
149 43 ▶ die "No seed source" unless $optional;
Branch: 1 branch
BranchTrueFalseTotal
unless $optional 2 41 43
150 41 return '';
151 }
152 45 $self->{"${name}func"} = $seedfunc;
153 45 $seed = $seedfunc->($len);
154 }
155  
156 5447 return $seed;
157 }
158  
159 2744 ▶sub _get_personalization {
Subroutine _get_personalization: called CC=9 SCAR=22.0
160 2744 my ($self, $params) = @_;
161 2744 my $name = 'personalize';
162 2744 my $autoname = "auto$name";
163  
164 2744 my $seed;
165 2744 ▶ if (defined $params->{$name} && !ref $params->{$name}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{$name} and not ref $params->{$name}) { } 2688 56 2744
Condition100%3/3
defined $params->{$name} and not ref $params->{$name}
!ll&&!rl&&r
5422688
MC/DC100%2/2
defined $params->{$name} and not ref $params->{$name}
defined $params->{$name} not ref $params->{$name}
Truth table100%3/3
A and not(B)
A= defined $params->{$name}B= not ref $params->{$name}
ABresult
0X0
100
111
166 2688 $seed = $params->{$name};
167 }
168 else {
169 56 my $seedfunc;
170 56 ▶ $seedfunc = $params->{$name} if ref $params->{$name} eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $params->{$name} eq "CODE" 2 54 56
171 56 ▶ if ($params->{$autoname} || $params->{auto}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{$autoname} or $params->{"auto"}) 11 45 56
Condition100%3/3
$params->{$autoname} or $params->{"auto"}
l!l&&r!l&&!r
2945
MC/DC100%2/2
$params->{$autoname} or $params->{"auto"}
$params->{$autoname} $params->{"auto"}
Truth table100%3/3
A or B
A= $params->{$autoname}B= $params->{"auto"}
ABresult
1X1
011
000
172 die "Invalid version"
173 11 ▶ if defined $params->{version} && $params->{version};
Branch: 1 branch
BranchTrueFalseTotal
if defined $params->{"version"} and $params->{"version"} 0 11 11
Condition33%1/3
defined $params->{"version"} and $params->{"version"}
!ll&&!rl&&r
1100
MC/DC0%0/2
defined $params->{"version"} and $params->{"version"}
defined $params->{"version"} $params->{"version"}
Truth table33%1/3
A and B
A= defined $params->{"version"}B= $params->{"version"}
ABresult
0X0
100
111
174 11 my $version = 0;
175 11 ▶ $seedfunc = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
176 11 my @nums = ($$, $<, $>, time);
177 11 my @strings = ($0, $(, $));
178  
179 11 return join('',
180 "$version\0",
181 pack("N" x @nums, @nums),
182 pack("Z" x @strings, @strings),
183 );
184 11 };
185 }
186 # Personalization strings are recommended, but optional.
187 56 ▶ return '' unless $seedfunc;
Branch: 1 branch
BranchTrueFalseTotal
unless $seedfunc 43 13 56
188 13 $seed = $seedfunc->();
189 }
190  
191 2701 return $seed;
192 }
193  
194 5559 ▶sub _check_reseed {
Subroutine _check_reseed: called CC=8 SCAR=20.9
195 5559 my ($self) = @_;
196  
197 5559 my $reseed = 0;
198 5559 my $pid = $self->{pid};
199 5559 ▶ $reseed = 1 if defined $pid && $pid != $$;
Branch: 1 branch
BranchTrueFalseTotal
if defined $pid and $pid != $$ 8 5551 5559
Condition100%3/3
defined $pid and $pid != $$
!ll&&!rl&&r
5482698
MC/DC100%2/2
defined $pid and $pid != $$
defined $pid $pid != $$
Truth table100%3/3
A and B
A= defined $pidB= $pid != $$
ABresult
0X0
100
111
200 5559 ▶ $reseed = 1 if $self->{reseed_counter} >= $self->{reseed_interval};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"reseed_counter"} >= $self->{"reseed_interval"} 0 5559 5559
201  
202 5559 ▶ if ($reseed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($reseed) 8 5551 5559
203 8 ▶ die "No seed source" if !$self->{seedfunc};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"seedfunc"} 0 8 8
204 8 $self->_reseed($self->{seedfunc}->($self->{seedlen}));
205 8 ▶ $self->{pid} = $$ if $self->{fork_safe};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"fork_safe"} 8 0 8
206 8 ▶ $self->{cache} = '' if defined $self->{cache};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"cache"} 2 6 8
207 }
208  
209 5559 return 1;
210 }
211  
212 2746 ▶sub initialize {
Subroutine initialize: called CC=5 SCAR=16.1
Pod documented
213 2746 my ($self, %params) = @_;
214  
215 2746 my $seed = $self->_get_seed('seed', $self->{seedlen}, \%params);
216 2744 my $nonce = $self->_get_seed('nonce', int(($self->{seedlen} / 2) + 1),
217 \%params, 1);
218 2744 my $personal = $self->_get_personalization(\%params);
219  
220 2744 $self->_seed("$seed$nonce$personal");
221  
222 2744 ▶ if ($params{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params{"cache"}) 5 2739 2744
223 5 $self->{cache} = '';
224 5 $self->{cache_size} = $params{cache};
225 }
226  
227 2744 ▶ if ($params{fork_safe} || (!exists $params{fork_safe} && $params{auto})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params{"fork_safe"} or not exists $params{"fork_safe"} and $params{"auto"}) 26 2718 2744
Condition83%5/6
$params{"fork_safe"} or not exists $params{"fork_safe"} and $params{"auto"}
l!l&&r!l&&!r
1792718
not exists $params{"fork_safe"} and $params{"auto"}
!ll&&!rl&&r
027189
MC/DC66%2/3
$params{"fork_safe"} or not exists $params{"fork_safe"} and $params{"auto"}
$params{"fork_safe"} not exists $params{"fork_safe"} $params{"auto"}
Truth table75%3/4
A or not(B) and C
A= $params{"fork_safe"}B= not exists $params{"fork_safe"}C= $params{"auto"}
ABCresult
1XX1
0111
00X0
0100
228 26 $self->{fork_safe} = 1;
229 26 $self->{pid} = $$;
230 }
231  
232 2744 return 1;
233 }
234  
235 =head2 $drbg->generate($bytes, $additional_data)
236  
237 Generate and return $bytes bytes. There is a limit per algorithm on the number of bytes that can be requested at once, which is at least 2^10.
238  
239 If $additional_data is specified, add this additional data to the DRBG.
240  
241 If the cache flag was specified on instantiation, bytes will be satisfied from
242 the cache first, unless $additional_data was specified.
243  
244 =cut
245  
246 5548 ▶sub generate {
Subroutine generate: called CC=7 SCAR=19.5
Pod documented
247 5548 my ($self, $len, $seed) = @_;
248  
249 return $self->_generate($len, $seed)
250 5548 ▶ if !defined $self->{cache} || defined $seed;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $self->{"cache"} or defined $seed 5466 82 5548
Condition66%2/3
not defined $self->{"cache"} or defined $seed
l!l&&r!l&&!r
5466082
MC/DC50%1/2
not defined $self->{"cache"} or defined $seed
not defined $self->{"cache"} defined $seed
Truth table66%2/3
not(A) or B
A= not defined $self->{"cache"}B= defined $seed
ABresult
1X1
011
000
251  
252 82 $self->_check_reseed;
253  
254 82 my $data = '';
255 82 my $left = $len;
256 82 my $cache = \$self->{cache};
257 82 ▶ $$cache = $self->_generate($self->{cache_size}) if !length($$cache);
Branch: 1 branch
BranchTrueFalseTotal
unless length $$cache 7 75 82
258 82 ▶ while ($left > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($left > 0) 86 82 168
259 86 ▶ my $chunk_size = $left > length($$cache) ? length($$cache) : $left;
Branch: 1 branch
BranchTrueFalseTotal
$left > length $$cache ? : 4 82 86
260 86 $data .= substr($$cache, 0, $chunk_size, '');
261 86 $left = $len - length($data);
262 86 ▶ $$cache = $self->_generate($self->{cache_size}) if !length($$cache);
Branch: 1 branch
BranchTrueFalseTotal
unless length $$cache 4 82 86
263 }
264  
265 82 return $data;
266 }
267  
268 =head2 $drbg->rand([$n], [$num])
269  
270 Like Perl's rand, but cryptographically secure. Uses 32-bit values.
271  
272 Accepts an additional argument, $num, which is the number of values to return.
273 Defaults to 1 (obviously).
274  
275 Note that just as with Perl's rand, there may be a slight bias with this
276 function. Use randitems if that matters to you.
277  
278 Returns an array if $num is specified and a single item if it is not.
279  
280 =cut
281  
282 3 ▶sub rand {
Subroutine rand: called CC=4 SCAR=13.9
Pod documented
283 3 my ($self, $n, $num) = @_;
284  
285 3 my $single = !defined $num;
286  
287 3 ▶ $n = 1 unless defined $n;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n 1 2 3
288 3 ▶ $num = 1 unless defined $num;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $num 2 1 3
289  
290 3 my $bytes = $self->generate($num * 4);
291 3 my @data = map { $_ / 2.0 / (2 ** 31) * $n } unpack("N[$num]", $bytes);
292 3 ▶ return $single ? $data[0] : @data;
Branch: 1 branch
BranchTrueFalseTotal
$single ? : 2 1 3
293 }
294  
295 =head2 $drbg->randitems($n, $items)
296  
297 Select randomly and uniformly from the arrayref $items $n times.
298  
299 =cut
300  
301 6 ▶sub randitems {
Subroutine randitems: called CC=5 SCAR=16.2
Pod documented
302 6 my ($self, $n, $items) = @_;
303  
304 6 my $len = scalar @$items;
305 6 my @results;
306 6 my $values = [
307 {bytes => 1, pack => 'C', max => 256},
308 {bytes => 2, pack => 'n', max => 65536},
309 {bytes => 4, pack => 'N', max => 2 ** 31},
310 ];
311 6 ▶ my $params = $values->[$len <= 256 ? 0 : $len <= 65536 ? 1 : 2];
Branch: 2 branches
BranchTrueFalseTotal
$len <= 256 ? : 6 0 6
$len <= 65536 ? : 0 0 0
312  
313 # Getting this computation right is important so as not to bias the
314 # data. $len & $len - 1 is true iff $len is not a power of two.
315 6 my $max = $params->{max};
316 6 my $mask = $max - 1;
317 6 ▶ if ($len & ($len - 1)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($len & $len - 1) { } 4 2 6
318 4 $max = $max - ($max % $len);
319 }
320 else {
321 2 $mask = $len - 1;
322 }
323  
324 6 my $pack = "$params->{pack}\[$n\]";
325 6 ▶ while (@results < $n) {
Branch: 1 branch
BranchTrueFalseTotal
if (@results < $n) 8 6 14
326 8 my $bytes = $self->generate($params->{bytes} * $n);
327  
328 8 my @data = map { $_ & $mask } grep { $_ < $max } unpack($pack, $bytes);
329 8 push @results, map { $items->[$_ % $len] } @data;
330 }
331  
332 6 return splice(@results, 0, $n);
333 }
334  
335 =head2 $drbg->randbytes($n, $items)
336  
337 Select randomly and uniformly from the characters in arrayref $items $n times.
338 Returns a byte string.
339  
340 This function works just like randitems, but is more efficient if generating a
341 sequence of bytes as a string instead of an array.
342  
343 =cut
344  
345 3 ▶sub randbytes {
Subroutine randbytes: called CC=3 SCAR=11.0
Pod documented
346 3 my ($self, $n, $items) = @_;
347  
348 3 my $len = scalar @$items;
349 3 my $results = '';
350  
351 # Getting this computation right is important so as not to bias the
352 # data. $len & $len - 1 is true iff $len is not a power of two.
353 3 my $max = 256;
354 3 ▶ my $filter = sub { return $_[0]; };
Subroutine __ANON__: called CC=1 SCAR=0.0
355 3 ▶ if ($len & ($len - 1)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($len & $len - 1) 2 1 3
356 2 $max = $max - ($max % $len);
357 2 my $esc = sprintf '\x%02x', $max + 1;
358 3 ▶ $filter = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
359 3 my $s = shift;
360 3 eval "\$s =~ tr/$esc-\\xff//d"; ## no critic(ProhibitStringyEval)
361 3 return $s;
362 2 };
363 }
364  
365 3 ▶ while (length $results < $n) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $results < $n) 4 3 7
366 4 my $bytes = $filter->($self->generate($n));
367 4 $results .= join '', map { $items->[$_ % $len] } unpack('C*', $bytes);
368 }
369  
370 3 return substr($results, 0, $n);
371 }
372  
373 =head1 AUTHOR
374  
375 brian m. carlson, C<< <sandals at crustytoothpaste.net> >>
376  
377 =head1 BUGS
378  
379 Please report any bugs or feature requests to C<bug-crypt-drbg at rt.cpan.org>, or through
380 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Crypt-DRBG>. I will be notified, and then you'll
381 automatically be notified of progress on your bug as I make changes.
382  
383  
384  
385  
386 =head1 SUPPORT
387  
388 You can find documentation for this module with the perldoc command.
389  
390 perldoc Crypt::DRBG
391  
392  
393 You can also look for information at:
394  
395 =over 4
396  
397 =item * RT: CPAN's request tracker (report bugs here)
398  
399 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Crypt-DRBG>
400  
401 =item * AnnoCPAN: Annotated CPAN documentation
402  
403 L<http://annocpan.org/dist/Crypt-DRBG>
404  
405 =item * CPAN Ratings
406  
407 L<http://cpanratings.perl.org/d/Crypt-DRBG>
408  
409 =item * Search CPAN
410  
411 L<http://search.cpan.org/dist/Crypt-DRBG/>
412  
413 =back
414  
415  
416 =head1 ACKNOWLEDGEMENTS
417  
418  
419 =head1 LICENSE AND COPYRIGHT
420  
421 Copyright 2015 brian m. carlson.
422  
423 This program is distributed under the MIT (X11) License:
424 L<http://www.opensource.org/licenses/mit-license.php>
425  
426 Permission is hereby granted, free of charge, to any person
427 obtaining a copy of this software and associated documentation
428 files (the "Software"), to deal in the Software without
429 restriction, including without limitation the rights to use,
430 copy, modify, merge, publish, distribute, sublicense, and/or sell
431 copies of the Software, and to permit persons to whom the
432 Software is furnished to do so, subject to the following
433 conditions:
434  
435 The above copyright notice and this permission notice shall be
436 included in all copies or substantial portions of the Software.
437  
438 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
439 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
440 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
441 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
442 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
443 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
444 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
445 OTHER DEALINGS IN THE SOFTWARE.
446  
447  
448 =cut
449  
450 15 1; # End of Crypt::DRBG
↑ Summary lib/Crypt/DRBG/Hash.pm »