1Crypt::Random::Seed(3)User Contributed Perl DocumentationCrypt::Random::Seed(3)
2
3
4

NAME

6       Crypt::Random::Seed - Simple method to get strong randomness
7

VERSION

9       Version 0.03
10

SYNOPSIS

12         use Crypt::Random::Seed;
13
14         my $source = new Crypt::Random::Seed;
15         die "No strong sources exist" unless defined $source;
16         my $seed_string = $source->random_bytes(4);
17         my @seed_values = $source->random_values(4);
18
19         # Only non-blocking sources
20         my $nonblocking_source = Crypt::Random::Seed->new( NonBlocking=>1 );
21
22         # Blacklist sources (never choose the listed sources)
23         my $nowin32_source = Crypt::Random::Seed->new( Never=>['Win32'] );
24
25         # Whitelist sources (only choose from these sources)
26         my $devr_source = Crypt::Random::Seed->new( Only=>['TESHA2'] );
27
28         # Supply a custom source.
29         my $user_src = Crypt::Random::Seed->new( Source=>sub { myfunc(shift) } );
30         # Or supply a list of [name, sub, is_blocking, is_strong]
31         $user_src = Crypt::Random::Seed->new(
32            Source=>['MyRandomFunction',sub {myfunc(shift)},0,1] );
33
34         # Given a source there are a few things we can do:
35         say "My randomness source is ", $source->name();
36         say "I am a blocking source" if $source->is_blocking();
37         say "I am a strong randomness source" if $source->is_strong()
38         say "Four 8-bit numbers:",
39             join(",", map { ord $source->random_bytes(1) } 1..4);'
40         say "Four 32-bit numbers:", join(",", $source->random_values(4));
41

DESCRIPTION

43       A simple mechanism to get strong randomness.  The main purpose of this
44       module is to provide a simple way to generate a seed for a PRNG such as
45       Math::Random::ISAAC, for use in cryptographic key generation, or as the
46       seed for an upstream module such as Bytes::Random::Secure.  Flags for
47       requiring non-blocking sources are allowed, as well as a very simple
48       method for plugging in a source.
49
50       The randomness sources used are, in order:
51
52       User supplied.
53           If the constructor is called with a Source defined, then it is
54           used.  It is not checked vs. other flags (NonBlocking, Never,
55           Only).
56
57       Win32 Crypto API.
58           This will use "CryptGenRandom" on Windows 2000 and "RtlGenRand" on
59           Windows XP and newer.  According to MSDN, these are well-seeded
60           CSPRNGs (FIPS 186-2 or AES-CTR), so will be non-blocking.
61
62       EGD / PRNGD.
63           This looks for sockets that speak the EGD
64           <http://egd.sourceforge.net/> protocol, including PRNGD
65           <http://prngd.sourceforge.net/>.  These are userspace entropy
66           daemons that are commonly used by OpenSSL, OpenSSH, and GnuGP.  The
67           locations searched are "/var/run/egd-pool", "/dev/egd-pool",
68           "/etc/egd-pool", and "/etc/entropy".  EGD is blocking, while PRNGD
69           is non-blocking (like the Win32 API, it is really a seeded CSPRNG).
70           However there is no way to tell them apart, so we treat it as
71           blocking.  If your O/S supports /dev/random, consider HAVEGED
72           <http://www.issihosts.com/haveged/> as an alternative (a system
73           daemon that refills /dev/random as needed).
74
75       /dev/random.
76           The strong source of randomness on most UNIX-like systems.  Cygwin
77           uses this, though it maps to the Win32 API.  On almost all systems
78           this is a blocking source of randomness -- if it runs out of
79           estimated entropy, it will hang until more has come into the
80           system.  If this is an issue, which it often is on embedded
81           devices, running a tool such as HAVEGED
82           <http://www.issihosts.com/haveged/> will help immensely.
83
84       /dev/urandom.
85           A nonblocking source of randomness that we label as weak, since it
86           will continue providing output even if the actual entropy has been
87           exhausted.
88
89       TESHA2.
90           Crypt::Random::TESHA2 is a Perl module that generates random bytes
91           from an entropy pool fed with timer/scheduler variations.
92           Measurements and tests are performed on installation to determine
93           whether the source is considered strong or weak.  This is entirely
94           in portable userspace, which is good for ease of use, but really
95           requires user verification that it is working as expected if we
96           expect it to be strong.  The concept is similar to
97           Math::TrulyRandom though updated to something closer to what
98           TrueRand 2.1 does vs. the obsolete version 1 that Math::TrulyRandom
99           implements.  It is very slow and has wide speed variability across
100           platforms : I've seen numbers ranging from 40 to 150,000 bits per
101           second.
102
103       A source can also be supplied in the constructor.  Each of these
104       sources will have its debatable points about perceived strength.  E.g.
105       Why is /dev/urandom considered weak while Win32 is strong?  Can any
106       userspace method such as TrueRand or TESHA2 be considered strong?
107
108   SOURCE TABLE
109       This table summarizes the default sources:
110
111         +------------------+-------------+------------+--------------------+
112         |      SOURCE      |  STRENGTH   |  BLOCKING  |       NOTE         |
113         |------------------+-------------+------------+--------------------|
114         | RtlGenRandom     |   Strong(1) |     No     | Default WinXP+     |
115         |------------------+-------------+------------+--------------------|
116         | CryptGenRandom   |   Strong(1) |     No     | Default Win2000    |
117         |------------------+-------------+------------+--------------------|
118         | EGD              |   Strong    |    Yes(2)  | also PRNGD, etc.   |
119         |------------------+-------------+------------+--------------------|
120         | /dev/random      |   Strong    |    Yes     | Typical UNIX       |
121         |------------------+-------------+------------+--------------------|
122         | /dev/urandom     |    Weak     |     No     | Typical UNIX NB    |
123         |------------------+-------------+------------+--------------------|
124         | TESHA2-strong    |   Strong    |     No     |                    |
125         |------------------+-------------+------------+--------------------|
126         | TESHA2-weak      |    Weak     |     No     |                    |
127         +------------------+-------------+------------+--------------------+
128
129       The alias 'Win32' can be used in whitelist and blacklist and will match
130       both the Win32 sources "RtlGenRandom" and "CryptGenRandom".  The alias
131       'TESHA2' may be similarly used and matches both the weak and strong
132       sources.
133
134         1) Both CryptGenRandom and RtlGenRandom are considered strong by this
135            package, even though both are seeded CSPRNGs so should be the equal of
136            /dev/urandom in this respect.  The CryptGenRandom function used in
137            Windows 2000 has some known issues so should be considered weaker.
138
139         2) EGD is blocking, PRNGD is not.  We cannot tell the two apart.  There are
140            other software products that use the same protocol, and each will act
141            differently.  E.g. EGD mixes in system entropy on every request, while
142            PRNGD mixes on a time schedule.
143
144   STRENGTH
145       In theory, a strong generator will provide true entropy.  Even if a
146       third party knew a previous result and the entire state of the
147       generator at any time up to when their value was returned, they could
148       still not effectively predict the result of the next returned value.
149       This implies the generator must either be blocking to wait for entropy
150       (e.g. /dev/random) or go through some possibly time-consuming process
151       to gather it (TESHA2, EGD, the HAVEGE daemon refilling /dev/random).
152       Note: strong in this context means practically strong, as most
153       computers don't have a true hardware entropy generator.  The goal is to
154       make all the attackers ill-gotten knowledge give them no better
155       solution than if they did not have the information.
156
157       Creating a satisfactory strength measurement is problematic.  The Win32
158       Crypto API is considered "strong" by most customers and every other
159       Perl module, however it is a well seeded CSPRNG according to the MSDN
160       docs, so is not a strong source based on the definition in the previous
161       paragraph.  Similarly, almost all sources consider /dev/urandom to be
162       weak, as once it runs out of entropy it returns a deterministic
163       function based on its state (albeit one that cannot be run either
164       direction from a returned result if the internal state is not known).
165
166       Because of this confusion, I have removed the "Weak" configuration
167       option that was present in version 0.01.  It will now be ignored.  You
168       should be able to use a combination of whitelist, blacklist, and the
169       source's "is_strong" return value to decide if this meets your needs.
170       On Win32, you really only have a choice of Win32 and TESHA2.  The
171       former is going to be what most people want, and can be chosen even
172       with non-blocking set.  On most UNIX systems, "/dev/random" will be
173       chosen for blocking and "/dev/urandom" for non-blocking, which is what
174       should be done in most cases.
175
176   BLOCKING
177       EGD and /dev/random are blocking sources.  This means that if they run
178       out of estimated entropy, they will pause until they've collected more.
179       This means your program also pauses.  On typical workstations this may
180       be a few seconds or even minutes.  On an isolated network server this
181       may cause a delay of hours or days.  EGD is proactive about gathering
182       more entropy as fast as it can.  Running a tool such as the HAVEGE
183       daemon or timer_entropyd can make /dev/random act like a non-blocking
184       source, as the entropy daemon will wake up and refill the pool almost
185       instantly.
186
187       Win32, PRNGD, and /dev/urandom are fast nonblocking sources.  When they
188       run out of entropy, they use a CSPRNG to keep supplying data at high
189       speed.  However this means that there is no additional entropy being
190       supplied.
191
192       TESHA2 is nonblocking, but can be very slow.  /dev/random can be faster
193       if run on a machine with lots of activity.  On an isolated server,
194       TESHA2 may be much faster.  Also note that the blocking sources such as
195       EGD and /dev/random both try to maintain reasonably large entropy
196       pools, so small requests can be supplied without blocking.
197
198   IN PRACTICE
199       Use the default to get the best source known.  If you know more about
200       the sources available, you can use a whitelist, blacklist, or a custom
201       source.  In general, to get the best source (typically Win32 or
202       /dev/random):
203
204         my $source = Crypt::Random::Seed->new();
205
206       To get a good non-blocking source (Win32 or /dev/urandom):
207
208         my $source = Crypt::Random::Seed->new(NonBlocking => 1);
209

METHODS

211   new
212       The constructor with no arguments will find the first available source
213       in its fixed list and return an object that performs the defined
214       methods.  If no sources could be found (quite unusual) then the
215       returned value will be undef.
216
217       Optional parameters are passed in as a hash and may be mixed.
218
219       NonBlocking => boolean
220
221       Only non-blocking sources will be allowed.  In practice this means EGD
222       and /dev/random will not be chosen (except on FreeBSD where it is non-
223       blocking).
224
225       Only => [list of strings]
226
227       Takes an array reference containing one or more string source names.
228       No source whose name does not match one of these strings will be
229       chosen.  The string 'Win32' will match either of the Win32 sources, and
230       'TESHA2' will match both the strong and weak versions.
231
232       Never => [list of strings]
233
234       Takes an array reference containing one or more string source names.
235       No source whose name matches one of these strings will be chosen.  The
236       string 'Win32' will match either of the Win32 sources, and 'TESHA2'
237       will match both the strong and weak versions.
238
239       Source => sub { ... }
240
241       Uses the given anonymous subroutine as the generator.  The subroutine
242       will be given an integer (the argument to "random_bytes") and should
243       return random data in a string of the given length.  For the purposes
244       of the other object methods, the returned object will have the name
245       'User', and be considered non-blocking and non-strong.
246
247       Source => ['name', sub { ... }, is_blocking, is_strong]
248
249       Similar to the simpler source routine, but also allows the other source
250       parameters to be defined.  The name may not be one of the standard
251       names listed in the "name" section.
252
253   random_bytes($n)
254       Takes an integer and returns a string of that size filled with random
255       data.  Returns an empty string if the argument is not defined or is not
256       more than zero.
257
258   random_values($n)
259       Takes an integer and returns an array of that many random 32-bit
260       values.  Returns an empty array if the argument is not defined or is
261       not more than zero.
262
263   name
264       Returns the text name of the random source.  This will be one of:
265       "User" for user defined, "CryptGenRandom" for Windows 2000 Crypto API,
266       "RtlGenRand" for Windows XP and newer Crypto API, "EGD" for a known
267       socket speaking the EGD protocol, "/dev/random" for the UNIX-like
268       strong randomness source, "/dev/urandom" for the UNIX-like non-blocking
269       randomness source, "TESHA2-strong" for the userspace entropy method
270       when considered strong, "TESHA2-weak" for the userspace entropy method
271       when considered weak.  Other methods may be supported in the future.
272       User supplied sources may be named anything other than one of the
273       defined names.
274
275   is_strong
276       Returns 1 or 0 indicating whether the source is considered a strong
277       source of randomness.  See the "STRENGTH" section for more discussion
278       of what this means, and the source table for what we think of each
279       source.
280
281   is_blocking
282       Returns 1 or 0 indicating whether the source can block on read.  Be
283       aware that even if a source doesn't block, it may be extremely slow.
284

AUTHORS

286       Dana Jacobsen <dana@acm.org>
287

ACKNOWLEDGEMENTS

289       To the best of my knowledge, Max Kanat-Alexander was the original
290       author of the Perl code that uses the Win32 API.  I used his code as a
291       reference.
292
293       David Oswald gave me a lot of help with API discussions and code
294       reviews.
295

SEE ALSO

297       The first question one may ask is "Why yet another module of this
298       type?"  None of the modules on CPAN quite fit my needs, hence this.
299       Some alternatives:
300
301   Crypt::Random::Source
302       A comprehensive system using multiple plugins.  It has a nice API, but
303       uses Any::Moose which means you're loading up Moose or Mouse just to
304       read a few bytes from /dev/random.  It also has a very long dependency
305       chain, with on the order of 40 modules being installed as prerequisites
306       (depending of course on whether you use any of them on other projects).
307       Lastly, it requires at least Perl 5.8, which may or may not matter to
308       you.  But it matters to some other module builders who end up with the
309       restriction in their modules.
310
311   Crypt::URandom
312       A great little module that is almost what I was looking for.
313       Crypt::Random::Seed will act the same if given the constructor:
314
315         my $source = Crypt::Random::Seed->new(
316            NonBlocking => 1,
317            Only => [qw(/dev/random /dev/urandom Win32)]
318         );
319         croak "No randomness source available" unless defined $source;
320
321       Or you can leave out the "Only" and have TESHA2 as a backup.
322
323   Crypt::Random
324       Requires Math::Pari which makes it unacceptable in some environments.
325       Has more features (numbers in arbitrary bigint intervals or bit sizes).
326       Crypt::Random::Seed is taking a simpler approach, just handling
327       returning octets and letting upstream modules handle the rest.
328
329   Data::Entropy
330       An interesting module that contains a source encapsulation (defaults to
331       system rand, but has many plugins), a good CSPRNG (AES in counter
332       mode), and the Data::Entropy::Algorithms module with many ways to get
333       bits, ints, bigints, floats, bigfloats, shuffles, and so forth.  From
334       my perspective, the algorithms module is the highlight, with a lot of
335       interesting code.
336
337   Upstream modules
338       Some modules that could use this module to help them:
339       Bytes::Random::Secure, Math::Random::ISAAC, Math::Random::Secure, and
340       Math::Random::MT to name a few.
341
343       Copyright 2013 by Dana Jacobsen <dana@acm.org>
344
345       This program is free software; you can redistribute it and/or modify it
346       under the same terms as Perl itself.
347
348       The software is provided "AS IS", without warranty of any kind, express
349       or implied, including but not limited to the warranties of
350       merchantability, fitness for a particular purpose and noninfringement.
351       In no event shall the authors or copyright holders be liable for any
352       claim, damages or other liability, whether in an action of contract,
353       tort or otherwise, arising from, out of or in connection with the
354       software or the use or other dealings in the software.
355
356
357
358perl v5.34.0                      2021-07-22            Crypt::Random::Seed(3)
Impressum