Entropy/Source.pm

filter: Statementstmt 93.6% 117 / 125 Branchbran 82.4% 61 / 74 Conditioncond 77.7% 7 / 9 MC/DCmcdc 66.6% 4 / 6 Subroutinesub 100% 13 / 13 Podpod 100% 5 / 5 totaltotal 89.2% 207 / 232 CC 41 SCAR 23.0
CC
41
Cov
89%
get_prob
17.1
get_octet
12.5
get_int
10.0
CRAP 10.0
« Entropy/RawSource/CryptCounter.pm ↑ Summary Entropy.pm »
1 =head1 NAME
2  
3 Data::Entropy::Source - encapsulated source of entropy
4  
5 =head1 SYNOPSIS
6  
7 use Data::Entropy::Source;
8  
9 $source = Data::Entropy::Source->new($handle, "sysread");
10  
11 $c = $source->get_octet;
12 $str = $source->get_bits(17);
13 $i = $source->get_int(12345);
14 $i = $source->get_int(Math::BigInt->new("1000000000000"));
15 $j = $source->get_prob(1, 2);
16  
17 =head1 DESCRIPTION
18  
19 An object of this class encapsulates a source of entropy
20 (randomness). Methods allow entropy to be dispensed in any
21 quantity required, even fractional bits. An entropy source object
22 should not normally be used directly. Rather, it should be used to
23 support higher-level entropy-consuming algorithms, such as those in
24 L<Data::Entropy::Algorithms>.
25  
26 This type of object is constructed as a layer over a raw entropy source
27 which does not supply methods to extract arbitrary amounts of entropy.
28 The raw entropy source is expected to dispense only entire octets at
29 a time. The B</dev/random> devices on some versions of Unix constitute
30 such a source, for example. The raw entropy source is accessed
31 via the C<IO::Handle> interface. This interface may be supplied by
32 classes other than C<IO::Handle> itself, as is done for example by
33 C<Data::Entropy::RawSource::CryptCounter>.
34  
35 If two entropy sources of this class are given exactly the same raw
36 entropy data, for example by reading from the same file, and exactly the
37 same sequence of C<get_> method calls is made to them, then they will
38 return exactly the same values from those calls. (Calls with numerical
39 arguments that have the same numerical value but are of different
40 types count as the same for this purpose.) This means that a run of an
41 entropy-using algorithm can be made completely deterministic if desired.
42  
43 =cut
44  
45 package Data::Entropy::Source;
46  
47 19 ▶{ use 5.006; }
Subroutine BEGIN: called CC=1 SCAR=0.0
48 19 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
49 19 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
50  
51 19 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
52  
53 19 our $VERSION = "0.010";
54  
55 =head1 CONSTRUCTOR
56  
57 =over
58  
59 =item Data::Entropy::Source->new(RAW_SOURCE, READ_STYLE)
60  
61 Constructs and returns an entropy source object based on the given raw
62 source. RAW_SOURCE must be an I/O handle referring to a source of entropy
63 that can be read one octet at a time. Specifically, it must support
64 either the C<getc> or C<sysread> method described in L<IO::Handle>.
65 READ_STYLE must be a string, either "getc" or "sysread", indicating which
66 method should be used to read from the raw source. No methods other
67 than the one specified will ever be called on the raw source handle,
68 so a full implementation of C<IO::Handle> is not required.
69  
70 The C<sysread> method should be used with B</dev/random> and its ilk,
71 because buffering would be very wasteful of entropy and might consequently
72 block other processes that require entropy. C<getc> should be preferred
73 when reading entropy from a regular file, and it is the more convenient
74 interface to implement when a non-I/O object is being used for the handle.
75  
76 =cut
77  
78 20 ▶sub new {
Subroutine new: called CC=3 SCAR=11.4
Pod documented
79 20 my($class, $rawsrc, $readstyle) = @_;
80 20 ▶ croak "no raw entropy source given" unless defined $rawsrc;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rawsrc 0 20 20
81 20 ▶ croak "read style `$readstyle' not recognised"
Branch: 1 branch
BranchTrueFalseTotal
unless $readstyle =~ /\A(?:getc|sysread)\z/ 0 20 20
82 unless $readstyle =~ /\A(?:getc|sysread)\z/;
83 20 return bless({
84 rawsrc => $rawsrc,
85 readstyle => $readstyle,
86 limit => 1,
87 num => 0,
88 }, $class);
89 }
90  
91 =back
92  
93 =head1 METHODS
94  
95 =over
96  
97 =item $source->get_octet
98  
99 Returns an octet of entropy, as a string of length one. This provides
100 direct access to the raw entropy source.
101  
102 =cut
103  
104 72891 ▶sub get_octet {
Subroutine get_octet: called CC=7 SCAR=25.3
Pod documented
105 72891 my($self) = @_;
106 72891 ▶ if($self->{readstyle} eq "getc") {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'readstyle'} eq 'getc') { } 72891 0 72891
elsif ($self->{'readstyle'} eq 'sysread') { } 0 0 0
107 72891 my $errno = $!;
108 72891 $! = 0;
109 72891 my $octet = $self->{rawsrc}->getc;
110 72891 ▶ unless(defined $octet) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $octet) 4 72887 72891
111 4 my $errmsg = $!;
112 4 ▶ unless($errmsg) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($errmsg) 0 4 4
113 0 $errmsg = "EOF";
114 0 $! = $errno;
115 }
116 4 croak "entropy source failed: $errmsg";
117 }
118 72887 $! = $errno;
119 72887 return $octet;
120 } elsif($self->{readstyle} eq "sysread") {
121 0 my $octet;
122 0 my $n = $self->{rawsrc}->sysread($octet, 1);
123 0 ▶ croak "entropy source failed: ".(defined($n) ? $! : "EOF")
Branch: 2 branches
BranchTrueFalseTotal
unless $n 0 0 0
defined $n ? : 0 0 0
124 unless $n;
125 0 return $octet;
126 }
127 }
128  
129 # ->_get_small_int may be used only with a native integer argument, up to 256.
130  
131 35031 ▶sub _get_small_int {
Subroutine _get_small_int: called CC=3 SCAR=11.1
132 35031 my($self, $limit) = @_;
133 19 ▶ use integer;
Subroutine BEGIN: called CC=1 SCAR=0.0
134 35031 my $reqlimit = $limit << 15;
135 35031 while(1) {
136 35031 ▶ while($self->{limit} < $reqlimit) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"limit"} < $reqlimit) 15363 35030 50393
137 15363 $self->{num} = ($self->{num} << 8) +
138 ord($self->get_octet);
139 15362 $self->{limit} <<= 8;
140 }
141 35030 my $rep = $self->{limit} / $limit;
142 35030 my $uselimit = $rep * $limit;
143 35030 ▶ if($self->{num} < $uselimit) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"num"} < $uselimit) 35030 0 35030
144 35030 my $num = $self->{num} / $rep;
145 35030 $self->{num} %= $rep;
146 35030 $self->{limit} = $rep;
147 35030 return $num;
148 }
149 0 $self->{num} -= $uselimit;
150 0 $self->{limit} -= $uselimit;
151 }
152 }
153  
154 # ->_put_small_int is used to return the unused portion of some entropy that
155 # was extracted using ->_get_small_int.
156  
157 2945 ▶sub _put_small_int {
Subroutine _put_small_int: called CC=1 SCAR=0.0
158 2945 my($self, $limit, $num) = @_;
159 2945 $self->{limit} *= $limit;
160 2945 $self->{num} = $self->{num} * $limit + $num;
161 }
162  
163 =item $source->get_bits(NBITS)
164  
165 Returns NBITS bits of entropy, as a string of octets. If NBITS is
166 not a multiple of eight then the last octet in the string has its most
167 significant bits set to zero.
168  
169 =cut
170  
171 222 ▶sub get_bits {
Subroutine get_bits: called CC=3 SCAR=11.0
Pod documented
172 222 my($self, $nbits) = @_;
173 222 my $nbytes = $nbits >> 3;
174 222 $nbits &= 7;
175 222 my $str = "";
176 222 ▶ $str .= $self->get_octet while $nbytes--;
Branch: 1 branch
BranchTrueFalseTotal
$nbytes-- and do { $str .= $self->get_octet } 2053 221 2274
177 221 ▶ $str .= chr($self->_get_small_int(1 << $nbits)) if $nbits;
Branch: 1 branch
BranchTrueFalseTotal
if $nbits 193 28 221
178 221 return $str;
179 }
180  
181 =item $source->get_int(LIMIT)
182  
183 LIMIT must be a positive integer. Returns a uniformly-distributed
184 random number between zero inclusive and LIMIT exclusive. LIMIT may be
185 either a native integer, a C<Math::BigInt> object, or an integer-valued
186 C<Math::BigRat> object; the returned number is of the same type.
187  
188 This method dispenses a non-integer number of bits of entropy.
189 For example, if LIMIT is 10 then the result contains approximately 3.32
190 bits of entropy. The minimum non-zero amount of entropy that can be
191 obtained is 1 bit, with LIMIT = 2.
192  
193 =cut
194  
195 33043 ▶sub _break_int {
Subroutine _break_int: called CC=4 SCAR=13.9
196 33043 my($num) = @_;
197 33043 my $type = ref($num);
198 33043 ▶ $num = $num->as_number if $type eq "Math::BigRat";
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "Math::BigRat" 500 32543 33043
199 33043 my @limbs;
200 33043 ▶ while($num != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($num != 0) 92552 33043 125595
201 92552 my $l = $num & 255;
202 92552 ▶ $l = $l->numify if $type ne "";
Branch: 1 branch
BranchTrueFalseTotal
if $type ne "" 4475 88077 92552
203 92552 push @limbs, $l;
204 92552 $num >>= 8;
205 }
206 33043 return \@limbs;
207 }
208  
209 27343 ▶sub get_int {
Subroutine get_int: called CC=10 SCAR=23.0
Pod documented
210 27343 my($self, $limit) = @_;
211 27343 my $type = ref($limit);
212 27343 my $max = _break_int($limit - 1);
213 27343 my $len = @$max;
214 27343 my @num_limbs;
215 27343 ▶ if($len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($len) 27082 261 27343
216 27147 TRY_AGAIN:
217 my $i = $len;
218 27147 my $ml = $max->[--$i];
219 27147 my $nl = $self->_get_small_int($ml + 1);
220 27146 @num_limbs = ($nl);
221 27146 ▶ while($i && $nl == $ml) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i and $nl == $ml) 4231 27081 31312
Condition100%3/3
$i and $nl == $ml
!ll&&!rl&&r
6977201044231
MC/DC100%2/2
$i and $nl == $ml
$i $nl == $ml
Truth table100%3/3
A and B
A= $iB= $nl == $ml
ABresult
0X0
100
111
222 4231 $ml = $max->[--$i];
223 4231 $nl = $self->_get_small_int(256);
224 4231 ▶ if($nl > $ml) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nl > $ml) 65 4166 4231
225 65 $self->_put_small_int(255-$ml, $nl-$ml-1);
226 65 goto TRY_AGAIN;
227 }
228 4166 push @num_limbs, $nl;
229 }
230 27081 ▶ push @num_limbs, ord($self->get_octet) while $i--;
Branch: 1 branch
BranchTrueFalseTotal
$i-- and do { push @num_limbs, ord $self->get_octet } 53426 27080 80506
231 }
232 27341 ▶ my $num = $type eq "" ? 0 : Math::BigInt->new(0);
Branch: 1 branch
BranchTrueFalseTotal
$type eq '' ? : 26067 1274 27341
233 27341 ▶ for(my $i = $len; $i--; ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i--) 84665 27341 112006
234 84665 my $l = $num_limbs[$len-1-$i];
235 84665 ▶ $l = Math::BigInt->new($l) if $type ne "";
Branch: 1 branch
BranchTrueFalseTotal
if $type ne "" 4466 80199 84665
236 84665 $num += $l << ($i << 3);
237 }
238 27341 ▶ $num = Math::BigRat->new($num) if $type eq "Math::BigRat";
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "Math::BigRat" 500 26841 27341
239 27341 return $num;
240 }
241  
242 =item $source->get_prob(PROB0, PROB1)
243  
244 PROB0 and PROB1 must be non-negative integers, not both zero.
245 They may each be either a native integer, a C<Math::BigInt> object,
246 or an integer-valued C<Math::BigRat> objects; types may be mixed.
247 Returns either 0 or 1, with relative probabilities PROB0 and PROB1.
248 That is, the probability of returning 0 is PROB0/(PROB0+PROB1), and the
249 probability of returning 1 is PROB1/(PROB0+PROB1).
250  
251 This method dispenses a fraction of a bit of entropy. The maximum
252 amount of entropy that can be obtained is 1 bit, with PROB0 = PROB1.
253 The more different the probabilities are the less entropy is obtained.
254 For example, if PROB0 = 1 and PROB1 = 2 then the result contains
255 approximately 0.918 bits of entropy.
256  
257 =cut
258  
259 3034 ▶sub get_prob {
Subroutine get_prob: called CC=17 SCAR=28.4
Pod documented
260 3034 my($self, $prob0, $prob1) = @_;
261 3034 ▶ croak "probabilities must be non-negative"
Branch: 1 branch
BranchTrueFalseTotal
unless $prob0 >= 0 and $prob1 >= 0 0 3034 3034
Condition33%1/3
$prob0 >= 0 and $prob1 >= 0
!ll&&!rl&&r
003034
MC/DC0%0/2
$prob0 >= 0 and $prob1 >= 0
$prob0 >= 0 $prob1 >= 0
Truth table33%1/3
A and B
A= $prob0 >= 0B= $prob1 >= 0
ABresult
0X0
100
111
262 unless $prob0 >= 0 && $prob1 >= 0;
263 3034 ▶ if($prob0 == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if ($prob0 == 0) { } 49 2985 3034
elsif ($prob1 == 0) { } 135 2850 2985
264 49 ▶ croak "can't have nothing possible" if $prob1 == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $prob1 == 0 0 49 49
265 49 return 1;
266 } elsif($prob1 == 0) {
267 135 return 0;
268 }
269 2850 my $max0 = _break_int($prob0 - 1);
270 2850 my $maxt = _break_int($prob0 + $prob1 - 1);
271 2850 my $len = @$maxt;
272 2850 ▶ push @$max0, (0) x ($len - @$max0) unless @$max0 == $len;
Branch: 1 branch
BranchTrueFalseTotal
unless @$max0 == $len 823 2027 2850
273 2880 TRY_AGAIN:
274 my $maybe0 = 1;
275 2880 my $maybebad = 1;
276 2880 my($mtl, $m0l, $nl);
277 2880 for(my $i = $len - 1; ; $i--) {
278 3460 ▶ $nl = $self->_get_small_int(
Branch: 1 branch
BranchTrueFalseTotal
$i == $len - 1 ? : 2880 580 3460
279 $i == $len-1 ? $maxt->[-1] + 1 : 256);
280 3460 ▶ $m0l = $maybe0 ? $max0->[$i] : -1;
Branch: 1 branch
BranchTrueFalseTotal
$maybe0 ? : 3274 186 3460
281 3460 ▶ $mtl = $maybebad ? $maxt->[$i] : 256;
Branch: 1 branch
BranchTrueFalseTotal
$maybebad ? : 3277 183 3460
282 3460 ▶ my $lastlimb = $i ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$i ? : 1530 1930 3460
283 3460 ▶ if($nl < $m0l + $lastlimb) {
Branch: 3 branches
BranchTrueFalseTotal
if ($nl < $m0l + $lastlimb) { } 1628 1832 3460
elsif ($nl > $m0l and $nl < $mtl + $lastlimb) { } 1222 610 1832
elsif ($nl > $mtl) { } 30 580 610
284 1628 $self->_put_small_int($m0l + $lastlimb, $nl);
285 1628 return 0;
286 ▶ } elsif($nl > $m0l && $nl < $mtl + $lastlimb) {
Condition100%3/3
$nl > $m0l and $nl < $mtl + $lastlimb
!ll&&!rl&&r
3942161222
MC/DC100%2/2
$nl > $m0l and $nl < $mtl + $lastlimb
$nl > $m0l $nl < $mtl + $lastlimb
Truth table100%3/3
A and B
A= $nl > $m0lB= $nl < $mtl + $lastlimb
ABresult
0X0
100
111
287 1222 $self->_put_small_int($mtl + $lastlimb - $m0l - 1,
288 $nl - $m0l - 1);
289 1222 return 1;
290 } elsif($nl > $mtl) {
291 30 $self->_put_small_int(255 - $mtl, $nl - $mtl - 1);
292 30 goto TRY_AGAIN;
293 }
294 580 ▶ $maybe0 = 0 if $nl > $m0l;
Branch: 1 branch
BranchTrueFalseTotal
if $nl > $m0l 186 394 580
295 580 ▶ $maybebad = 0 if $nl < $mtl;
Branch: 1 branch
BranchTrueFalseTotal
if $nl < $mtl 183 397 580
296 }
297 }
298  
299 =back
300  
301 =head1 SEE ALSO
302  
303 L<Data::Entropy>,
304 L<Data::Entropy::Algorithms>,
305 L<Data::Entropy::RawSource::CryptCounter>,
306 L<Data::Entropy::RawSource::Local>,
307 L<IO::Handle>
308  
309 =head1 AUTHOR
310  
311 Andrew Main (Zefram) <zefram@fysh.org>
312  
313 Maintained by Robert Rothenberg <perl@rhizomnic.com>
314  
315 =head1 COPYRIGHT
316  
317 Copyright (C) 2006, 2007, 2009, 2011, 2025-2026
318 Andrew Main (Zefram) <zefram@fysh.org>
319  
320 =head1 LICENSE
321  
322 This module is free software; you can redistribute it and/or modify it
323 under the same terms as Perl itself.
324  
325 =cut
326  
327 19 1;
« Entropy/RawSource/CryptCounter.pm ↑ Summary Entropy.pm »