Math-Random-Secure-0.080001/0000775000175000017500000000000013061347621013772 5ustar frewfrewMath-Random-Secure-0.080001/lib/0000775000175000017500000000000013061347621014540 5ustar frewfrewMath-Random-Secure-0.080001/lib/Math/0000775000175000017500000000000013061347621015431 5ustar frewfrewMath-Random-Secure-0.080001/lib/Math/Random/0000775000175000017500000000000013061347621016651 5ustar frewfrewMath-Random-Secure-0.080001/lib/Math/Random/Secure/0000775000175000017500000000000013061347621020077 5ustar frewfrewMath-Random-Secure-0.080001/lib/Math/Random/Secure/RNG.pm0000644000175000017500000001374713061347621021075 0ustar frewfrewpackage Math::Random::Secure::RNG; $Math::Random::Secure::RNG::VERSION = '0.080001'; # ABSTRACT: The underlying PRNG, as an object. use Moo; use Math::Random::ISAAC; use Crypt::Random::Source::Factory; use constant ON_WINDOWS => $^O =~ /Win32/i ? 1 : 0; use if ON_WINDOWS, 'Crypt::Random::Source::Strong::Win32'; has seeder => ( is => 'ro', lazy => 1, builder => '_build_seeder', ); # Default to a 512-bit key, which should be impossible to break. I wrote # to the author of ISAAC and he said it's fine to not use a full 256 # integers to seed ISAAC. has seed_size => ( is => 'ro', # isa => 'Int', default => 64, ); has seed => ( is => 'rw', isa => \&_check_seed, lazy => 1, builder => '_build_seed', clearer => 'clear_seed', predicate => 'has_seed', ); has rng => ( is => 'ro', lazy => 1, builder => '_build_rng', handles => ['irand', 'rand'], clearer => 'clear_rng', ); has _for_pid => ( is => 'rw', default => sub { $$ }, ); sub _clear_for_pid { shift->_for_pid($$) } before qw(irand rand) => '_maybe_clear_seed'; sub _maybe_clear_seed { my $self = shift; if ($self->_for_pid != $$) { $self->clear_seed; $self->_clear_for_pid; } } sub BUILD { my ($self) = @_; if ($self->seed_size < 8) { warn "Setting seed_size to less than 8 is not recommended"; } } sub _check_seed { my ($seed) = @_; if (length($seed) < 8) { warn "Your seed is less than 8 bytes (64 bits). It could be" . " easy to crack"; } # If it looks like we were seeded with a 32-bit integer, warn the # user that they are making a dangerous, easily-crackable mistake. # We do this during BUILD so that it happens during srand() in # Math::Secure::RNG. elsif (length($seed) <= 10 and $seed =~ /^\d+$/) { warn "RNG seeded with a 32-bit integer, this is easy to crack"; } # _check_seed is used as a type constraint, so needs to return 1. return 1; } sub _build_seeder { my $factory = Crypt::Random::Source::Factory->new(); # On Windows, we want to always pick Crypt::Random::Source::Strong::Win32, # which this will do. if (ON_WINDOWS) { return $factory->get_strong; } my $source = $factory->get; # Never allow rand() to be used as a source, it cannot possibly be # cryptographically strong with 2^15 or 2^32 bits for its seed. if ($source->isa('Crypt::Random::Source::Weak::rand')) { $source = $factory->get_strong; } return $source; } sub _build_seed { my ($self) = @_; return $self->seeder->get($self->seed_size); } sub _build_rng { my ($self) = @_; my @seed_ints = unpack('L*', $self->seed); my $rng = Math::Random::ISAAC->new(@seed_ints); # One part of having a cryptographically-secure RNG is not being # able to see the seed in the internal state of the RNG. $self->clear_seed; # It's faster to skip the frontend interface of Math::Random::ISAAC # and just use the backend directly. However, in case the internal # code of Math::Random::ISAAC changes at some point, we do make sure # that the {backend} element actually exists first. return $rng->{backend} ? $rng->{backend} : $rng; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Math::Random::Secure::RNG - The underlying PRNG, as an object. =head1 VERSION version 0.080001 =head1 SYNOPSIS use Math::Random::Secure::RNG; my $rng = Math::Random::Secure::RNG->new(); my $int = $rng->irand(); =head1 DESCRIPTION This represents a random number generator, as an object. Generally, you shouldn't have to worry about this, and you should just use L. But if for some reason you want to modify how the random number generator works or you want an object-oriented interface to a random-number generator, you can use this. =head1 METHODS =head2 irand Generates a random unsigned 32-bit integer. =head2 rand Generates a random floating-point number greater than or equal to 0 and less than 1. =head1 ATTRIBUTES These are all options that can be passed to C or called as methods on an existing object. =head2 rng The underlying random number generator. Defaults to an instance of L. =head2 seed The random data used to seed L, as a string of bytes. This should be large enough to properly seed L. This means I, it should be 8 bytes (64 bits) and more ideally, 32 bytes (256 bits) or 64 bytes (512 bits). For an idea of how large your seed should be, see L for information on how long it would take to brute-force seeds of each size. Note that C should not be an integer, but a B. It is very important that the seed be large enough, and also that the seed be very random. B By default, we use a 512-bit (64 byte) seed. If L continues to hold true, it will be approximately 1000 years before computers can brute-force a 512-bit (64 byte) seed at any reasonable speed (and physics suggests that computers will never actually become that fast, although there could always be improvements or new methods of computing we can't now imagine, possibly making Moore's Law continue to hold true forever). If you pass this to C, L and L will be ignored. =head2 seeder An instance of L that will be used to get the seed for L. =head2 seed_size How much data (in bytes) should be read using L to seed L. Defaults to 64 bytes (which is 512 bits). See L for more info about what is a reasonable seed size. =head1 SEE ALSO L =head1 AUTHORS =over 4 =item * Max Kanat-Alexander =item * Arthur Axel "fREW" Schmidt =back =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2010 by BugzillaSource, Inc. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) =cut Math-Random-Secure-0.080001/lib/Math/Random/Secure.pm0000644000175000017500000002317713061347621020445 0ustar frewfrewpackage Math::Random::Secure; $Math::Random::Secure::VERSION = '0.080001'; # ABSTRACT: Cryptographically-secure, cross-platform replacement for rand() use strict; use 5.008; use base qw(Exporter); use Math::Random::Secure::RNG; # ISAAC, a 32-bit generator, should only be capable of generating numbers # between 0 and 2^32 - 1. We want _to_float to generate numbers possibly # including 0, but always less than 1.0. Dividing the integer produced # by irand() by this number should do that exactly. use constant DIVIDE_BY => 2**32; our $RNG; our @EXPORT_OK = qw(rand srand irand); sub rand (;$) { my ($limit) = @_; my $int = irand(); return _to_float($int, $limit); } sub irand (;$) { my ($limit) = @_; Math::Random::Secure::srand() if !defined $RNG; my $int = $RNG->irand(); if (defined $limit) { # We can't just use the mod operator because it will bias # our output. Search for "modulo bias" on the Internet for # details. This is slower than mod(), but does not have a bias, # as demonstrated by our uniform.t test. return int(_to_float($int, $limit)); } return $int; } sub srand (;$) { my ($value) = @_; if (defined $RNG) { if (defined $value) { $RNG->seed($value); } else { $RNG->clear_seed; } $RNG->clear_rng; } else { my %args; if (defined $value) { $args{seed} = $value; } $RNG = Math::Random::Secure::RNG->new(%args); } # This makes srand return the seed and also makes sure that we # get the seed right now, if no $value was passed. return $RNG->seed; } sub _to_float { my ($integer, $limit) = @_; $limit = 1 if !$limit; return ($integer / DIVIDE_BY) * $limit; } __PACKAGE__ __END__ =pod =encoding UTF-8 =head1 NAME Math::Random::Secure - Cryptographically-secure, cross-platform replacement for rand() =head1 VERSION version 0.080001 =head1 SYNOPSIS # Replace rand(). use Math::Random::Secure qw(rand); # Get a random number between 0 and 1 my $float = rand(); # Get a random integer (faster than int(rand)) use Math::Random::Secure qw(irand); my $int = irand(); # Random integer between 0 and 9 inclusive. $int = irand(10); # Random floating-point number greater than or equal to 0.0 and # less than 10.0. $float = rand(10); =head1 DESCRIPTION This module is intended to provide a cryptographically-secure replacement for Perl's built-in C function. "Crytographically secure", in this case, means: =over =item * No matter how many numbers you see generated by the random number generator, you cannot guess the future numbers, and you cannot guess the seed. =item * There are so many possible seeds that it would take decades, centuries, or millenia for an attacker to try them all. =item * The seed comes from a source that generates relatively strong random data on your platform, so the seed itself will be as random as possible. See L for more information about the underlying systems used to implement all of these guarantees, and some important caveats if you're going to use this module for some very-high-security purpose. =back =head1 METHODS =head2 rand Should work exactly like Perl's built-in C. Will automatically call C if C has never been called in this process or thread. There is one limitation--Math::Random::Secure is backed by a 32-bit random number generator. So if you are on a 64-bit platform and you specify a limit that is greater than 2^32, you are likely to get less-random data. =head2 srand B Under normal circumstances, you should B call this function, as C and C will automatically call it for you the first time they are used in a thread or process. Seeds the random number generator, much like Perl's built-in C, except that it uses a much larger and more secure seed. The seed should be passed as a string of bytes, at least 8 bytes in length, and more ideally between 32 and 64 bytes. (See L for more info.) If you do not pass a seed, a seed will be generated automatically using a secure mechanism. See L for more information. This function returns the seed that generated (or the seed that was passed in, if you passed one in). =head2 irand Works somewhat like L, except that it returns a 32-bit integer between 0 and 2^32. Should be faster than doing C. Note that because it returns 32-bit integers, specifying a limit greater than 2^32 will have no effect. =head1 IMPLEMENTATION DETAILS Currently, Math::Random::Secure is backed by L, a cryptographically-strong random number generator with no known serious weaknesses. If there are significant weaknesses found in ISAAC, we will change our backend to a more-secure random number generator. The goal is for Math::Random::Secure to be cryptographically strong, not to represent some specific random number generator. Math::Random::Secure seeds itself using L. The underlying implementation uses F on Unix-like platforms, and the C or C functions on Windows 2000 and above. (There is no support for versions of Windows before Windows 2000.) If any of these seeding sources are not available and you have other L modules installed, Math::Random::Secure will use those other sources to seed itself. =head2 Making Math::Random::Secure Even More Secure We use F on Unix-like systems, because one of the requirements of duplicating C is that we never block waiting for seed data, and F could do that. However, it's possible that F could run out of "truly random" data and start to use its built-in pseudo-random number generator to generate data. On most systems, this should still provide a very good seed for nearly all uses, but it may not be suitable for very high-security cryptographic circumstances. For Windows, there are known issues with C on Windows 2000 and versions of Windows XP before Service Pack 3. However, there is no other built-in method of getting secure random data on Windows, and I suspect that these issues will not be significant for most applications of Math::Random::Secure. If either of these situations are a problem for your use, you can create your own L object with a different "seeder" argument, and set C<$Math::Random::Secure::RNG> to your own instance of L. The "seeder" is an instance of L, which should allow you to use most random-data sources in existence for your seeder, should you wish. =head2 Seed Exhaustion Perl's built-in C reads 32 bits from F. By default, we read 512 bits. This means that we are more likely to exhaust available truly-random data than the built-in C is, and cause F to fall back on its psuedo-random number generator. Normally this is not a problem, since L is only called once per Perl process or thread, but it is something that you should be aware of if you are going to be in a situation where you have many new Perl processes or threads and you have very high security requirements (on the order of generating private SSH or GPG keypairs, SSL private keys, etc.). =head1 SEE ALSO =over =item L Describes the requirements and nature of a cryptographically-secure random number generator. =item L, More information about the Windows functions we use to seed ourselves. The article also has some information about the weaknesses in Windows 2000's C implementation. =item L A news article about the Windows 2000/XP CryptGenRandom weakness, fixed in Vista and XP Service Pack 3. =item L A description of ways to attack a random number generator, which can help in understanding why such a generator needs to be secure. =item L The underlying random-number generator and seeding code for Math::Random::Secure. =item L =item L =item L All of these modules contain generators for "truly random" data, but they don't contain a simple C replacement and they can be very slow. =back =head1 SUPPORT Right now, the best way to get support for Math::Random::Secure is to email the author using the email address in the L section below. =head1 BUGS Math::Random::Secure is relatively new, as of December 2010, but the modules that underlie it are very well-tested and have a long history. However, the author still welcomes all feedback and bug reports, particularly those having to do with the security assurances provided by this module. You can report a bug by emailing C or by using the RT web interface at L. If your bug report is security-sensitive, you may also email it directly to the author using the email address in the L section below. =head1 AUTHORS =over 4 =item * Max Kanat-Alexander =item * Arthur Axel "fREW" Schmidt =back =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2010 by BugzillaSource, Inc. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) =cut Math-Random-Secure-0.080001/Makefile.PL0000644000175000017500000000276013061347621015747 0ustar frewfrew# This file was automatically generated by Dist::Zilla::Plugin::MakeMaker v6.008. use strict; use warnings; use ExtUtils::MakeMaker; my %WriteMakefileArgs = ( "ABSTRACT" => "Cryptographically-secure, cross-platform replacement for rand()", "AUTHOR" => "Max Kanat-Alexander , Arthur Axel \"fREW\" Schmidt ", "CONFIGURE_REQUIRES" => { "ExtUtils::MakeMaker" => 0 }, "DISTNAME" => "Math-Random-Secure", "LICENSE" => "artistic_2", "NAME" => "Math::Random::Secure", "PREREQ_PM" => { "Crypt::Random::Source" => "0.07", "Math::Random::ISAAC" => "1.001", "Moo" => 2 }, "TEST_REQUIRES" => { "List::MoreUtils" => 0, "Test::More" => 0, "Test::SharedFork" => 0, "Test::Warn" => 0 }, "VERSION" => "0.080001", "test" => { "TESTS" => "t/*.t" } ); my %FallbackPrereqs = ( "Crypt::Random::Source" => "0.07", "List::MoreUtils" => 0, "Math::Random::ISAAC" => "1.001", "Moo" => 2, "Test::More" => 0, "Test::SharedFork" => 0, "Test::Warn" => 0 ); unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) { delete $WriteMakefileArgs{TEST_REQUIRES}; delete $WriteMakefileArgs{BUILD_REQUIRES}; $WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs; } delete $WriteMakefileArgs{CONFIGURE_REQUIRES} unless eval { ExtUtils::MakeMaker->VERSION(6.52) }; if ( $^O eq 'MSWin32' ) { $WriteMakefileArgs{PREREQ_PM}{'Crypt::Random::Source::Strong::Win32'} = '0'; } WriteMakefile(%WriteMakefileArgs); Math-Random-Secure-0.080001/META.json0000644000175000017500000000347613061347621015423 0ustar frewfrew{ "abstract" : "Cryptographically-secure, cross-platform replacement for rand()", "author" : [ "Max Kanat-Alexander ", "Arthur Axel \"fREW\" Schmidt " ], "dynamic_config" : 1, "generated_by" : "Dist::Zilla version 6.008, CPAN::Meta::Converter version 2.150005", "license" : [ "artistic_2" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "Math-Random-Secure", "prereqs" : { "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "develop" : { "requires" : { "Statistics::Test::RandomWalk" : "0", "Test::Pod" : "1.41" } }, "runtime" : { "recommends" : { "Math::Random::ISAAC::XS" : "0" }, "requires" : { "Crypt::Random::Source" : "0.07", "Math::Random::ISAAC" : "1.001", "Moo" : "2" } }, "test" : { "recommends" : { "Test::LeakTrace" : "0" }, "requires" : { "List::MoreUtils" : "0", "Test::More" : "0", "Test::SharedFork" : "0", "Test::Warn" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/frioux/Math-Random-Secure/issues" }, "homepage" : "https://github.com/frioux/Math-Random-Secure", "repository" : { "type" : "git", "url" : "https://github.com/frioux/Math-Random-Secure.git", "web" : "https://github.com/frioux/Math-Random-Secure" } }, "version" : "0.080001", "x_serialization_backend" : "Cpanel::JSON::XS version 3.0213" } Math-Random-Secure-0.080001/MANIFEST0000644000175000017500000000051513061347621015122 0ustar frewfrew# This file was automatically generated by Dist::Zilla::Plugin::Manifest v6.008. Changes LICENSE MANIFEST META.json META.yml Makefile.PL README cpanfile dist.ini lib/Math/Random/Secure.pm lib/Math/Random/Secure/RNG.pm t/author-pod-syntax.t t/author-uniform.t t/compile.t t/memory.t t/range.t t/release-changes_has_content.t t/seed.t Math-Random-Secure-0.080001/META.yml0000644000175000017500000000173113061347621015243 0ustar frewfrew--- abstract: 'Cryptographically-secure, cross-platform replacement for rand()' author: - 'Max Kanat-Alexander ' - 'Arthur Axel "fREW" Schmidt ' build_requires: List::MoreUtils: '0' Test::More: '0' Test::SharedFork: '0' Test::Warn: '0' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 1 generated_by: 'Dist::Zilla version 6.008, CPAN::Meta::Converter version 2.150005' license: artistic_2 meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Math-Random-Secure recommends: Math::Random::ISAAC::XS: '0' requires: Crypt::Random::Source: '0.07' Math::Random::ISAAC: '1.001' Moo: '2' resources: bugtracker: https://github.com/frioux/Math-Random-Secure/issues homepage: https://github.com/frioux/Math-Random-Secure repository: https://github.com/frioux/Math-Random-Secure.git version: '0.080001' x_serialization_backend: 'YAML::Tiny version 1.69' Math-Random-Secure-0.080001/t/0000775000175000017500000000000013061347621014235 5ustar frewfrewMath-Random-Secure-0.080001/t/release-changes_has_content.t0000644000175000017500000000222213061347621022031 0ustar frewfrew#!perl BEGIN { unless ($ENV{RELEASE_TESTING}) { print qq{1..0 # SKIP these tests are for release candidate testing\n}; exit } } use Test::More tests => 2; note 'Checking Changes'; my $changes_file = 'Changes'; my $newver = '0.080001'; my $trial_token = '-TRIAL'; SKIP: { ok(-e $changes_file, "$changes_file file exists") or skip 'Changes is missing', 1; ok(_get_changes($newver), "$changes_file has content for $newver"); } done_testing; # _get_changes copied and adapted from Dist::Zilla::Plugin::Git::Commit # by Jerome Quelin sub _get_changes { my $newver = shift; # parse changelog to find commit message open(my $fh, '<', $changes_file) or die "cannot open $changes_file: $!"; my $changelog = join('', <$fh>); close $fh; my @content = grep { /^$newver(?:$trial_token)?(?:\s+|$)/ ... /^\S/ } # from newver to un-indented split /\n/, $changelog; shift @content; # drop the version line # drop unindented last line and trailing blank lines pop @content while ( @content && $content[-1] =~ /^(?:\S|\s*$)/ ); # return number of non-blank lines return scalar @content; } Math-Random-Secure-0.080001/t/author-pod-syntax.t0000644000175000017500000000045413061347621020031 0ustar frewfrew#!perl BEGIN { unless ($ENV{AUTHOR_TESTING}) { print qq{1..0 # SKIP these tests are for testing by the author\n}; exit } } # This file was automatically generated by Dist::Zilla::Plugin::PodSyntaxTests. use strict; use warnings; use Test::More; use Test::Pod 1.41; all_pod_files_ok(); Math-Random-Secure-0.080001/t/author-uniform.t0000644000175000017500000000501713061347621017402 0ustar frewfrew#!/usr/bin/perl BEGIN { unless ($ENV{AUTHOR_TESTING}) { require Test::More; Test::More::plan(skip_all => 'these tests are for testing by the author'); } } use strict; use warnings; use Test::More; use Math::Random::Secure qw(rand irand); use Statistics::Test::RandomWalk 0.02; # 2% variation is acceptable. our $ACCEPTABLE = 0.02; our $BINS = 20; our $NUM_RUNS = 500_000; # We want a number that's more than half of 2^32 but doesn't # divide evenly into it. our $LARGE_LIMIT = 3_000_893_649; plan tests => (20 * $BINS) - (8 + 20 + 36 + 34); sub test_uniform { my ($name, $limit, $rng) = @_; $rng ||= \&rand; my $num_runs = $NUM_RUNS; if (defined $limit and $limit > $num_runs) { # Uncomment this line for more extensive testing. #$num_runs = $limit * 2; } my $tester = Statistics::Test::RandomWalk->new(); if ($rng == \&irand) { $tester->set_rescale_factor($limit || 2**32); $tester->set_data(sub { $rng->($limit) }, $num_runs); } else { my $divide_by; $divide_by = $limit - (1 / (2**32)) if $limit; $tester->set_data(sub { $limit ? $rng->($limit) / $divide_by : $rng->() }, $num_runs); } my $bins = $BINS; if (defined $limit and $limit == 64) { $bins = 16; } if (defined $limit and $limit < $bins and $limit > 1) { $bins = $limit; } my ($quant, $got, $expected) = $tester->test($bins); foreach my $i (0 .. scalar(@$got) - 1) { cmp_ok( abs($got->[$i] - $expected->[$i]) / $expected->[$i], '<', $ACCEPTABLE, "$name: Quantile $quant->[$i] is within 2% of the expected " . $expected->[$i]); } if ($ENV{TEST_VERBOSE}) { diag $tester->data_to_report($quant, $got, $expected); } } test_uniform('rand no limit'); test_uniform('rand limit .3', .3); test_uniform('rand limit .9', .9); test_uniform('rand limit 2', 2); test_uniform('rand limit 3', 3); test_uniform('rand limit 10', 10); test_uniform('rand limit 40', 40); test_uniform('rand limit 64', 64); test_uniform('rand limit 200', 200); test_uniform('rand limit 1_000_000', 1_000_000); test_uniform("rand limit $LARGE_LIMIT", $LARGE_LIMIT); test_uniform('irand no limit', undef, \&irand); test_uniform('irand limit 2', 2, \&irand); test_uniform('irand limit 3', 3, \&irand); test_uniform('irand limit 10', 10, \&irand); test_uniform('irand limit 40', 40, \&irand); test_uniform('irand limit 64', 64, \&irand); test_uniform('irand limit 200', 200, \&irand); test_uniform('irand limit 1_000_000', 1_000_000, \&irand); test_uniform("irand limit $LARGE_LIMIT", $LARGE_LIMIT, \&irand); Math-Random-Secure-0.080001/t/compile.t0000644000175000017500000000021213061347621016043 0ustar frewfrew#!/usr/bin/perl use strict; use warnings; use Test::More tests => 2; use_ok('Math::Random::Secure::RNG'); use_ok('Math::Random::Secure'); Math-Random-Secure-0.080001/t/memory.t0000644000175000017500000000144013061347621015727 0ustar frewfrew#!/usr/bin/perl # Tests that there are no memory leaks. # Taken from the Math::Random::ISAAC tests under the public domain # license. use strict; use warnings; use Test::More; use Math::Random::Secure; if (exists($INC{'Devel/Cover.pm'})) { plan skip_all => 'This test is not compatible with Devel::Cover'; } eval { require Test::LeakTrace; }; if ($@) { plan skip_all => 'Test::LeakTrace required to test memory leaks'; } plan tests => 3; Test::LeakTrace->import; no_leaks_ok(sub { for (0..10) { Math::Random::Secure::srand(); } }, 'srand does not leak memory'); no_leaks_ok(sub { for (0..30) { Math::Random::Secure::irand(); } }, 'irand does not leak memory'); no_leaks_ok(sub { for (0..30) { Math::Random::Secure::rand(); } }, 'rand does not leak memory'); Math-Random-Secure-0.080001/t/range.t0000644000175000017500000000233313061347621015515 0ustar frewfrew#!/usr/bin/perl use strict; use warnings; use Test::More tests => 16; use Math::Random::Secure qw(rand irand); use Data::Dumper; use List::MoreUtils qw(all); our $HOW_MANY = 10_000; sub check_range { my ($numbers, $type, $limit) = @_; $limit ||= 10; my $all_less = all { $_ < $limit } @$numbers; ok($all_less, "all $type less than $limit") or diag Dumper($numbers); my $all_more = all { $_ >= 0 } @$numbers; ok($all_more, "all $type greater or equal to 0") or diag Dumper($numbers); } my @numbers = map { rand(10) } (1..$HOW_MANY); check_range(\@numbers, 'floats'); my @ints = map { irand(10) } (1..$HOW_MANY); check_range(\@ints, 'integers'); my @made_ints = map { int(rand(10)) } (1..$HOW_MANY); check_range(\@made_ints, 'made integers'); my @zero_to_one = map { rand() } (1..$HOW_MANY); check_range(\@zero_to_one, 'zero to one', 1); my @all_ints = map { irand() } (1..$HOW_MANY); check_range(\@all_ints, 'full range integers', 2**32); my @floats_zero = map { rand(0) } (1..$HOW_MANY); check_range(\@floats_zero, 'zero floats', 1); my @ints_zero = map { irand(0) } (1..$HOW_MANY); check_range(\@ints_zero, 'zero ints', 1); my @ints_one = map { irand(1) } (1..$HOW_MANY); check_range(\@ints_one, 'one ints', 1); Math-Random-Secure-0.080001/t/seed.t0000644000175000017500000000342513061347621015344 0ustar frewfrew#!/usr/bin/perl use strict; use warnings; use Test::More; use Test::Warn; use Test::SharedFork; use Math::Random::Secure qw(srand irand); use Math::Random::Secure::RNG; my $seed = srand(); cmp_ok(length($seed), '==', 64, 'seed is the right size'); my @sequence_one = map { irand() } (1..100); srand($seed); my @sequence_two = map { irand() } (1..100); is_deeply(\@sequence_one, \@sequence_two, 'Same seed generates the same sequence'); srand(); my @sequence_different = map { irand() } (1..100); my $string1 = join(' ', @sequence_one); my $string2 = join(' ', @sequence_different); isnt($string2, $string1, 'Different seeds generate different sequences'); warning_like { Math::Random::Secure::RNG->new(seed_size => 4) } qr/Setting seed_size to less than/, "Using too-small of a seed size throws a warning"; my $int32 = 2**31; warning_like { srand($int32) } qr/RNG seeded with a 32-bit integer/, "srand: Using a 32-bit integer throws a warning"; warning_like { Math::Random::Secure::RNG->new(seed => $int32) } qr/RNG seeded with a 32-bit integer/, "RNG->new: Using a 32-bit integer throws a warning"; my $short_seed = "abcde"; warning_like { srand($short_seed) } qr/Your seed is less than/, "srand: Short seeds throw a warning"; warning_like { Math::Random::Secure::RNG->new(seed => $short_seed) } qr/Your seed is less than/, "RNG->new: Short seeds throw a warning"; unless (Math::Random::Secure::RNG::ON_WINDOWS()) { srand($seed); my $first = irand(); srand($seed); my $second = irand(); is($first, $second, 'Same seed (duh)'); srand($seed); my $pid = fork; die "Failed to fork: $!" if $pid == -1; if ($pid == 0) { my $third = irand(); isnt($first, $third, 'Seed gets rebuilt after fork'); exit; } else { waitpid($pid, 0) } } done_testing(); Math-Random-Secure-0.080001/dist.ini0000644000175000017500000000075713061347621015445 0ustar frewfrewname = Math-Random-Secure version = 0.080001 author = Max Kanat-Alexander author = Arthur Axel "fREW" Schmidt license = Artistic_2_0 copyright_holder = BugzillaSource, Inc copyright_year = 2010 [NextRelease] [@Git] [@Basic] [GithubMeta] issues = 1 [MetaJSON] [PodWeaver] [PkgVersion] [ReadmeFromPod] [PodSyntaxTests] [Prereqs::FromCPANfile] [Test::ChangesHasContent] [OSPrereqs / MSWin32] Crypt::Random::Source::Strong::Win32 = 0 Math-Random-Secure-0.080001/cpanfile0000644000175000017500000000072713061347621015502 0ustar frewfrew# 1.001 supports 64-bit systems. requires 'Math::Random::ISAAC' => 1.001; # 0.07 fixes a lot of important bugs and warnings. requires 'Crypt::Random::Source' => 0.07; requires 'Moo' => 2; recommends 'Math::Random::ISAAC::XS'; on 'develop' => sub { requires 'Statistics::Test::RandomWalk'; }; on 'test' => sub { requires 'Test::More'; requires 'Test::Warn'; requires 'List::MoreUtils'; requires 'Test::SharedFork'; recommends 'Test::LeakTrace'; }; Math-Random-Secure-0.080001/LICENSE0000644000175000017500000002153013061347621014776 0ustar frewfrewThis software is Copyright (c) 2010 by BugzillaSource, Inc. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Math-Random-Secure-0.080001/Changes0000644000175000017500000000403413061347621015264 0ustar frewfrewRevision history for Math-Random-Secure 0.080001 2017-03-12 15:45:36-07:00 America/Los_Angeles - Fix out of date docs 0.08 2016-10-16 12:26:27-07:00 America/Los_Angeles - Fix built dist (POD, in file versions, etc) 0.07 2016-10-16 12:08:57-07:00 America/Los_Angeles - Regenerate seed after forking - Switch from Any::Moose to Moo - Fix warning added in newer perls - Add missing Author Dep 0.06 Mon Jan 24 2011 - Only require ExtUtils::MakeMaker 6.12, to make things easier on people running Perl 5.8. 0.05 Fri Jan 07 2011 - Make irand() and rand() 2.5x faster. - Now, if you specify $Math::Random::Secure::RNG before calling srand(), the "seeder" of $Math::Random::Secure::RNG will be used by srand() instead of srand() overriding the seeder and using the default one found by Math::Random::Secure::RNG. - Remove META.yml, in an attempt to make CPAN.pm install this module properly (this is an attempt to force CPAN.pm to read the dynamic dependencies for this module). 0.04 Wed Jan 05 2011 - Require Crypt::Random::Source 0.07 to avoid various bugs and warnings. - Fix the version requirements for Windows so that CPAN will install the proper prerequisites there. 0.03 Thu Dec 30 2011 - Clear the seed after the first call to rand() or irand(), so that an attacker can't inspect the state of the RNG to determine the seed. - Only seed ourselves with 64 bytes (512 bits) intead of 1024 bytes (8192 bits). The author of ISAAC says that this is safe. - Add POD explaining seed sizes and the importance of seed randomness. - Warn users if they pass in a bad seed or set seed_size too small. - Fix some small code and POD issues (thanks to LpSolit) 0.02 Wed Dec 29 2011 - Remove the modulo bias from irand(). - Add a test that proves the uniformity of generated values. - Update the POD quite a bit. 0.01 Tue Dec 28 2011 - First release. Uses ISAAC as a backend and Crypt::Random::Source for seed data. Math-Random-Secure-0.080001/README0000644000175000017500000001714713061347621014662 0ustar frewfrewSYNOPSIS # Replace rand(). use Math::Random::Secure qw(rand); # Get a random number between 0 and 1 my $float = rand(); # Get a random integer (faster than int(rand)) use Math::Random::Secure qw(irand); my $int = irand(); # Random integer between 0 and 9 inclusive. $int = irand(10); # Random floating-point number greater than or equal to 0.0 and # less than 10.0. $float = rand(10); DESCRIPTION This module is intended to provide a cryptographically-secure replacement for Perl's built-in rand function. "Crytographically secure", in this case, means: * No matter how many numbers you see generated by the random number generator, you cannot guess the future numbers, and you cannot guess the seed. * There are so many possible seeds that it would take decades, centuries, or millenia for an attacker to try them all. * The seed comes from a source that generates relatively strong random data on your platform, so the seed itself will be as random as possible. See "IMPLEMENTATION DETAILS" for more information about the underlying systems used to implement all of these guarantees, and some important caveats if you're going to use this module for some very-high-security purpose. METHODS rand Should work exactly like Perl's built-in rand. Will automatically call srand if srand has never been called in this process or thread. There is one limitation--Math::Random::Secure is backed by a 32-bit random number generator. So if you are on a 64-bit platform and you specify a limit that is greater than 2^32, you are likely to get less-random data. srand Note: Under normal circumstances, you should not call this function, as rand and irand will automatically call it for you the first time they are used in a thread or process. Seeds the random number generator, much like Perl's built-in srand, except that it uses a much larger and more secure seed. The seed should be passed as a string of bytes, at least 8 bytes in length, and more ideally between 32 and 64 bytes. (See "seed" in Math::Random::Secure::RNG for more info.) If you do not pass a seed, a seed will be generated automatically using a secure mechanism. See "IMPLEMENTATION DETAILS" for more information. This function returns the seed that generated (or the seed that was passed in, if you passed one in). irand Works somewhat like "rand", except that it returns a 32-bit integer between 0 and 2^32. Should be faster than doing int(rand). Note that because it returns 32-bit integers, specifying a limit greater than 2^32 will have no effect. IMPLEMENTATION DETAILS Currently, Math::Random::Secure is backed by Math::Random::ISAAC, a cryptographically-strong random number generator with no known serious weaknesses. If there are significant weaknesses found in ISAAC, we will change our backend to a more-secure random number generator. The goal is for Math::Random::Secure to be cryptographically strong, not to represent some specific random number generator. Math::Random::Secure seeds itself using Crypt::Random::Source. The underlying implementation uses /dev/urandom on Unix-like platforms, and the RtlGenRandom or CryptGenRandom functions on Windows 2000 and above. (There is no support for versions of Windows before Windows 2000.) If any of these seeding sources are not available and you have other Crypt::Random::Source modules installed, Math::Random::Secure will use those other sources to seed itself. Making Math::Random::Secure Even More Secure We use /dev/urandom on Unix-like systems, because one of the requirements of duplicating rand is that we never block waiting for seed data, and /dev/random could do that. However, it's possible that /dev/urandom could run out of "truly random" data and start to use its built-in pseudo-random number generator to generate data. On most systems, this should still provide a very good seed for nearly all uses, but it may not be suitable for very high-security cryptographic circumstances. For Windows, there are known issues with CryptGenRandom on Windows 2000 and versions of Windows XP before Service Pack 3. However, there is no other built-in method of getting secure random data on Windows, and I suspect that these issues will not be significant for most applications of Math::Random::Secure. If either of these situations are a problem for your use, you can create your own Math::Random::Secure::RNG object with a different "seeder" argument, and set $Math::Random::Secure::RNG to your own instance of Math::Random::Secure::RNG. The "seeder" is an instance of Crypt::Random::Source::Base, which should allow you to use most random-data sources in existence for your seeder, should you wish. Seed Exhaustion Perl's built-in srand reads 32 bits from /dev/urandom. By default, we read 512 bits. This means that we are more likely to exhaust available truly-random data than the built-in srand is, and cause /dev/urandom to fall back on its psuedo-random number generator. Normally this is not a problem, since "srand" is only called once per Perl process or thread, but it is something that you should be aware of if you are going to be in a situation where you have many new Perl processes or threads and you have very high security requirements (on the order of generating private SSH or GPG keypairs, SSL private keys, etc.). SEE ALSO http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator Describes the requirements and nature of a cryptographically-secure random number generator. http://en.wikipedia.org/wiki/CryptGenRandom, More information about the Windows functions we use to seed ourselves. The article also has some information about the weaknesses in Windows 2000's CryptGenRandom implementation. http://www.computerworld.com/s/article/9048438/Microsoft_confirms_that_XP_contains_random_number_generator_bug A news article about the Windows 2000/XP CryptGenRandom weakness, fixed in Vista and XP Service Pack 3. http://en.wikipedia.org/wiki/Random_number_generator_attack A description of ways to attack a random number generator, which can help in understanding why such a generator needs to be secure. Math::Random::Secure::RNG The underlying random-number generator and seeding code for Math::Random::Secure. Crypt::Source::Random Crypt::Random Math::TrulyRandom All of these modules contain generators for "truly random" data, but they don't contain a simple rand replacement and they can be very slow. SUPPORT Right now, the best way to get support for Math::Random::Secure is to email the author using the email address in the "AUTHORS" section below. BUGS Math::Random::Secure is relatively new, as of December 2010, but the modules that underlie it are very well-tested and have a long history. However, the author still welcomes all feedback and bug reports, particularly those having to do with the security assurances provided by this module. You can report a bug by emailing bug-Math-Random-Secure@rt.cpan.org or by using the RT web interface at https://rt.cpan.org/Ticket/Display.html?Queue=Math-Random-Secure. If your bug report is security-sensitive, you may also email it directly to the author using the email address in the "AUTHORS" section below.