{
    "content": [
        {
            "type": "text",
            "text": "# Crypt::Random::Seed (perldoc)\n\n## NAME\n\nCrypt::Random::Seed - Simple method to get strong randomness\n\n## SYNOPSIS\n\nuse Crypt::Random::Seed;\nmy $source = new Crypt::Random::Seed;\ndie \"No strong sources exist\" unless defined $source;\nmy $seedstring = $source->randombytes(4);\nmy @seedvalues = $source->randomvalues(4);\n# Only non-blocking sources\nmy $nonblockingsource = Crypt::Random::Seed->new( NonBlocking=>1 );\n# Blacklist sources (never choose the listed sources)\nmy $nowin32source = Crypt::Random::Seed->new( Never=>['Win32'] );\n# Whitelist sources (only choose from these sources)\nmy $devrsource = Crypt::Random::Seed->new( Only=>['TESHA2'] );\n# Supply a custom source.\nmy $usersrc = Crypt::Random::Seed->new( Source=>sub { myfunc(shift) } );\n# Or supply a list of [name, sub, isblocking, isstrong]\n$usersrc = Crypt::Random::Seed->new(\nSource=>['MyRandomFunction',sub {myfunc(shift)},0,1] );\n# Given a source there are a few things we can do:\nsay \"My randomness source is \", $source->name();\nsay \"I am a blocking source\" if $source->isblocking();\nsay \"I am a strong randomness source\" if $source->isstrong()\nsay \"Four 8-bit numbers:\",\njoin(\",\", map { ord $source->randombytes(1) } 1..4);'\nsay \"Four 32-bit numbers:\", join(\",\", $source->randomvalues(4));\n\n## DESCRIPTION\n\nA simple mechanism to get strong randomness. The main purpose of this module is to provide a\nsimple way to generate a seed for a PRNG such as Math::Random::ISAAC, for use in cryptographic\nkey generation, or as the seed for an upstream module such as Bytes::Random::Secure. Flags for\nrequiring non-blocking sources are allowed, as well as a very simple method for plugging in a\nsource.\n\n## Sections\n\n- **NAME**\n- **VERSION**\n- **SYNOPSIS**\n- **DESCRIPTION**\n- **METHODS**\n- **AUTHORS**\n- **ACKNOWLEDGEMENTS**\n- **SEE ALSO** (5 subsections)\n- **COPYRIGHT**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "Crypt::Random::Seed",
        "section": "",
        "mode": "perldoc",
        "summary": "Crypt::Random::Seed - Simple method to get strong randomness",
        "synopsis": "use Crypt::Random::Seed;\nmy $source = new Crypt::Random::Seed;\ndie \"No strong sources exist\" unless defined $source;\nmy $seedstring = $source->randombytes(4);\nmy @seedvalues = $source->randomvalues(4);\n# Only non-blocking sources\nmy $nonblockingsource = Crypt::Random::Seed->new( NonBlocking=>1 );\n# Blacklist sources (never choose the listed sources)\nmy $nowin32source = Crypt::Random::Seed->new( Never=>['Win32'] );\n# Whitelist sources (only choose from these sources)\nmy $devrsource = Crypt::Random::Seed->new( Only=>['TESHA2'] );\n# Supply a custom source.\nmy $usersrc = Crypt::Random::Seed->new( Source=>sub { myfunc(shift) } );\n# Or supply a list of [name, sub, isblocking, isstrong]\n$usersrc = Crypt::Random::Seed->new(\nSource=>['MyRandomFunction',sub {myfunc(shift)},0,1] );\n# Given a source there are a few things we can do:\nsay \"My randomness source is \", $source->name();\nsay \"I am a blocking source\" if $source->isblocking();\nsay \"I am a strong randomness source\" if $source->isstrong()\nsay \"Four 8-bit numbers:\",\njoin(\",\", map { ord $source->randombytes(1) } 1..4);'\nsay \"Four 32-bit numbers:\", join(\",\", $source->randomvalues(4));",
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "VERSION",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "SYNOPSIS",
                "lines": 30,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 140,
                "subsections": []
            },
            {
                "name": "METHODS",
                "lines": 57,
                "subsections": []
            },
            {
                "name": "AUTHORS",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "ACKNOWLEDGEMENTS",
                "lines": 5,
                "subsections": []
            },
            {
                "name": "SEE ALSO",
                "lines": 3,
                "subsections": [
                    {
                        "name": "Crypt::Random::Source",
                        "lines": 7
                    },
                    {
                        "name": "Crypt::URandom",
                        "lines": 11
                    },
                    {
                        "name": "Crypt::Random",
                        "lines": 4
                    },
                    {
                        "name": "Data::Entropy",
                        "lines": 5
                    },
                    {
                        "name": "Upstream modules",
                        "lines": 3
                    }
                ]
            },
            {
                "name": "COPYRIGHT",
                "lines": 11,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "Crypt::Random::Seed - Simple method to get strong randomness\n",
                "subsections": []
            },
            "VERSION": {
                "content": "Version 0.03\n",
                "subsections": []
            },
            "SYNOPSIS": {
                "content": "use Crypt::Random::Seed;\n\nmy $source = new Crypt::Random::Seed;\ndie \"No strong sources exist\" unless defined $source;\nmy $seedstring = $source->randombytes(4);\nmy @seedvalues = $source->randomvalues(4);\n\n# Only non-blocking sources\nmy $nonblockingsource = Crypt::Random::Seed->new( NonBlocking=>1 );\n\n# Blacklist sources (never choose the listed sources)\nmy $nowin32source = Crypt::Random::Seed->new( Never=>['Win32'] );\n\n# Whitelist sources (only choose from these sources)\nmy $devrsource = Crypt::Random::Seed->new( Only=>['TESHA2'] );\n\n# Supply a custom source.\nmy $usersrc = Crypt::Random::Seed->new( Source=>sub { myfunc(shift) } );\n# Or supply a list of [name, sub, isblocking, isstrong]\n$usersrc = Crypt::Random::Seed->new(\nSource=>['MyRandomFunction',sub {myfunc(shift)},0,1] );\n\n# Given a source there are a few things we can do:\nsay \"My randomness source is \", $source->name();\nsay \"I am a blocking source\" if $source->isblocking();\nsay \"I am a strong randomness source\" if $source->isstrong()\nsay \"Four 8-bit numbers:\",\njoin(\",\", map { ord $source->randombytes(1) } 1..4);'\nsay \"Four 32-bit numbers:\", join(\",\", $source->randomvalues(4));\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "A simple mechanism to get strong randomness. The main purpose of this module is to provide a\nsimple way to generate a seed for a PRNG such as Math::Random::ISAAC, for use in cryptographic\nkey generation, or as the seed for an upstream module such as Bytes::Random::Secure. Flags for\nrequiring non-blocking sources are allowed, as well as a very simple method for plugging in a\nsource.\n\nThe randomness sources used are, in order:\n\nUser supplied.\nIf the constructor is called with a Source defined, then it is used. It is not checked vs.\nother flags (NonBlocking, Never, Only).\n\nWin32 Crypto API.\nThis will use \"CryptGenRandom\" on Windows 2000 and \"RtlGenRand\" on Windows XP and newer.\nAccording to MSDN, these are well-seeded CSPRNGs (FIPS 186-2 or AES-CTR), so will be\nnon-blocking.\n\nEGD / PRNGD.\nThis looks for sockets that speak the EGD <http://egd.sourceforge.net/> protocol, including\nPRNGD <http://prngd.sourceforge.net/>. These are userspace entropy daemons that are commonly\nused by OpenSSL, OpenSSH, and GnuGP. The locations searched are \"/var/run/egd-pool\",\n\"/dev/egd-pool\", \"/etc/egd-pool\", and \"/etc/entropy\". EGD is blocking, while PRNGD is\nnon-blocking (like the Win32 API, it is really a seeded CSPRNG). However there is no way to\ntell them apart, so we treat it as blocking. If your O/S supports /dev/random, consider\nHAVEGED <http://www.issihosts.com/haveged/> as an alternative (a system daemon that refills\n/dev/random as needed).\n\n/dev/random.\nThe strong source of randomness on most UNIX-like systems. Cygwin uses this, though it maps\nto the Win32 API. On almost all systems this is a blocking source of randomness -- if it\nruns out of estimated entropy, it will hang until more has come into the system. If this is\nan issue, which it often is on embedded devices, running a tool such as HAVEGED\n<http://www.issihosts.com/haveged/> will help immensely.\n\n/dev/urandom.\nA nonblocking source of randomness that we label as weak, since it will continue providing\noutput even if the actual entropy has been exhausted.\n\nTESHA2.\nCrypt::Random::TESHA2 is a Perl module that generates random bytes from an entropy pool fed\nwith timer/scheduler variations. Measurements and tests are performed on installation to\ndetermine whether the source is considered strong or weak. This is entirely in portable\nuserspace, which is good for ease of use, but really requires user verification that it is\nworking as expected if we expect it to be strong. The concept is similar to\nMath::TrulyRandom though updated to something closer to what TrueRand 2.1 does vs. the\nobsolete version 1 that Math::TrulyRandom implements. It is very slow and has wide speed\nvariability across platforms : I've seen numbers ranging from 40 to 150,000 bits per second.\n\nA source can also be supplied in the constructor. Each of these sources will have its debatable\npoints about perceived strength. E.g. Why is /dev/urandom considered weak while Win32 is strong?\nCan any userspace method such as TrueRand or TESHA2 be considered strong?\n\nSOURCE TABLE\nThis table summarizes the default sources:\n\n+------------------+-------------+------------+--------------------+\n|      SOURCE      |  STRENGTH   |  BLOCKING  |       NOTE         |\n|------------------+-------------+------------+--------------------|\n| RtlGenRandom     |   Strong(1) |     No     | Default WinXP+     |\n|------------------+-------------+------------+--------------------|\n| CryptGenRandom   |   Strong(1) |     No     | Default Win2000    |\n|------------------+-------------+------------+--------------------|\n| EGD              |   Strong    |    Yes(2)  | also PRNGD, etc.   |\n|------------------+-------------+------------+--------------------|\n| /dev/random      |   Strong    |    Yes     | Typical UNIX       |\n|------------------+-------------+------------+--------------------|\n| /dev/urandom     |    Weak     |     No     | Typical UNIX NB    |\n|------------------+-------------+------------+--------------------|\n| TESHA2-strong    |   Strong    |     No     |                    |\n|------------------+-------------+------------+--------------------|\n| TESHA2-weak      |    Weak     |     No     |                    |\n+------------------+-------------+------------+--------------------+\n\nThe alias 'Win32' can be used in whitelist and blacklist and will match both the Win32 sources\n\"RtlGenRandom\" and \"CryptGenRandom\". The alias 'TESHA2' may be similarly used and matches both\nthe weak and strong sources.\n\n1) Both CryptGenRandom and RtlGenRandom are considered strong by this\npackage, even though both are seeded CSPRNGs so should be the equal of\n/dev/urandom in this respect.  The CryptGenRandom function used in\nWindows 2000 has some known issues so should be considered weaker.\n\n2) EGD is blocking, PRNGD is not.  We cannot tell the two apart.  There are\nother software products that use the same protocol, and each will act\ndifferently.  E.g. EGD mixes in system entropy on every request, while\nPRNGD mixes on a time schedule.\n\nSTRENGTH\nIn theory, a strong generator will provide true entropy. Even if a third party knew a previous\nresult and the entire state of the generator at any time up to when their value was returned,\nthey could still not effectively predict the result of the next returned value. This implies the\ngenerator must either be blocking to wait for entropy (e.g. /dev/random) or go through some\npossibly time-consuming process to gather it (TESHA2, EGD, the HAVEGE daemon refilling\n/dev/random). Note: strong in this context means practically strong, as most computers don't\nhave a true hardware entropy generator. The goal is to make all the attackers ill-gotten\nknowledge give them no better solution than if they did not have the information.\n\nCreating a satisfactory strength measurement is problematic. The Win32 Crypto API is considered\n\"strong\" by most customers and every other Perl module, however it is a well seeded CSPRNG\naccording to the MSDN docs, so is not a strong source based on the definition in the previous\nparagraph. Similarly, almost all sources consider /dev/urandom to be weak, as once it runs out\nof entropy it returns a deterministic function based on its state (albeit one that cannot be run\neither direction from a returned result if the internal state is not known).\n\nBecause of this confusion, I have removed the \"Weak\" configuration option that was present in\nversion 0.01. It will now be ignored. You should be able to use a combination of whitelist,\nblacklist, and the source's \"isstrong\" return value to decide if this meets your needs. On\nWin32, you really only have a choice of Win32 and TESHA2. The former is going to be what most\npeople want, and can be chosen even with non-blocking set. On most UNIX systems, \"/dev/random\"\nwill be chosen for blocking and \"/dev/urandom\" for non-blocking, which is what should be done in\nmost cases.\n\nBLOCKING\nEGD and /dev/random are blocking sources. This means that if they run out of estimated entropy,\nthey will pause until they've collected more. This means your program also pauses. On typical\nworkstations this may be a few seconds or even minutes. On an isolated network server this may\ncause a delay of hours or days. EGD is proactive about gathering more entropy as fast as it can.\nRunning a tool such as the HAVEGE daemon or timerentropyd can make /dev/random act like a\nnon-blocking source, as the entropy daemon will wake up and refill the pool almost instantly.\n\nWin32, PRNGD, and /dev/urandom are fast nonblocking sources. When they run out of entropy, they\nuse a CSPRNG to keep supplying data at high speed. However this means that there is no\nadditional entropy being supplied.\n\nTESHA2 is nonblocking, but can be very slow. /dev/random can be faster if run on a machine with\nlots of activity. On an isolated server, TESHA2 may be much faster. Also note that the blocking\nsources such as EGD and /dev/random both try to maintain reasonably large entropy pools, so\nsmall requests can be supplied without blocking.\n\nIN PRACTICE\nUse the default to get the best source known. If you know more about the sources available, you\ncan use a whitelist, blacklist, or a custom source. In general, to get the best source\n(typically Win32 or /dev/random):\n\nmy $source = Crypt::Random::Seed->new();\n\nTo get a good non-blocking source (Win32 or /dev/urandom):\n\nmy $source = Crypt::Random::Seed->new(NonBlocking => 1);\n",
                "subsections": []
            },
            "METHODS": {
                "content": "new\nThe constructor with no arguments will find the first available source in its fixed list and\nreturn an object that performs the defined methods. If no sources could be found (quite unusual)\nthen the returned value will be undef.\n\nOptional parameters are passed in as a hash and may be mixed.\n\nNonBlocking => *boolean*\nOnly non-blocking sources will be allowed. In practice this means EGD and /dev/random will not\nbe chosen (except on FreeBSD where it is non-blocking).\n\nOnly => [*list of strings*]\nTakes an array reference containing one or more string source names. No source whose name does\nnot match one of these strings will be chosen. The string 'Win32' will match either of the Win32\nsources, and 'TESHA2' will match both the strong and weak versions.\n\nNever => [*list of strings*]\nTakes an array reference containing one or more string source names. No source whose name\nmatches one of these strings will be chosen. The string 'Win32' will match either of the Win32\nsources, and 'TESHA2' will match both the strong and weak versions.\n\nSource => sub { *...* }\nUses the given anonymous subroutine as the generator. The subroutine will be given an integer\n(the argument to \"randombytes\") and should return random data in a string of the given length.\nFor the purposes of the other object methods, the returned object will have the name 'User', and\nbe considered non-blocking and non-strong.\n\nSource => ['*name*', sub { *...* }, *isblocking*, *isstrong*]\nSimilar to the simpler source routine, but also allows the other source parameters to be\ndefined. The name may not be one of the standard names listed in the \"name\" section.\n\nrandombytes($n)\nTakes an integer and returns a string of that size filled with random data. Returns an empty\nstring if the argument is not defined or is not more than zero.\n\nrandomvalues($n)\nTakes an integer and returns an array of that many random 32-bit values. Returns an empty array\nif the argument is not defined or is not more than zero.\n\nname\nReturns the text name of the random source. This will be one of: \"User\" for user defined,\n\"CryptGenRandom\" for Windows 2000 Crypto API, \"RtlGenRand\" for Windows XP and newer Crypto API,\n\"EGD\" for a known socket speaking the EGD protocol, \"/dev/random\" for the UNIX-like strong\nrandomness source, \"/dev/urandom\" for the UNIX-like non-blocking randomness source,\n\"TESHA2-strong\" for the userspace entropy method when considered strong, \"TESHA2-weak\" for the\nuserspace entropy method when considered weak. Other methods may be supported in the future.\nUser supplied sources may be named anything other than one of the defined names.\n\nisstrong\nReturns 1 or 0 indicating whether the source is considered a strong source of randomness. See\nthe \"STRENGTH\" section for more discussion of what this means, and the source table for what we\nthink of each source.\n\nisblocking\nReturns 1 or 0 indicating whether the source can block on read. Be aware that even if a source\ndoesn't block, it may be extremely slow.\n",
                "subsections": []
            },
            "AUTHORS": {
                "content": "Dana Jacobsen <dana@acm.org>\n",
                "subsections": []
            },
            "ACKNOWLEDGEMENTS": {
                "content": "To the best of my knowledge, Max Kanat-Alexander was the original author of the Perl code that\nuses the Win32 API. I used his code as a reference.\n\nDavid Oswald gave me a lot of help with API discussions and code reviews.\n",
                "subsections": []
            },
            "SEE ALSO": {
                "content": "The first question one may ask is \"Why yet another module of this type?\" None of the modules on\nCPAN quite fit my needs, hence this. Some alternatives:\n",
                "subsections": [
                    {
                        "name": "Crypt::Random::Source",
                        "content": "A comprehensive system using multiple plugins. It has a nice API, but uses Any::Moose which\nmeans you're loading up Moose or Mouse just to read a few bytes from /dev/random. It also has a\nvery long dependency chain, with on the order of 40 modules being installed as prerequisites\n(depending of course on whether you use any of them on other projects). Lastly, it requires at\nleast Perl 5.8, which may or may not matter to you. But it matters to some other module builders\nwho end up with the restriction in their modules.\n"
                    },
                    {
                        "name": "Crypt::URandom",
                        "content": "A great little module that is almost what I was looking for. Crypt::Random::Seed will act the\nsame if given the constructor:\n\nmy $source = Crypt::Random::Seed->new(\nNonBlocking => 1,\nOnly => [qw(/dev/random /dev/urandom Win32)]\n);\ncroak \"No randomness source available\" unless defined $source;\n\nOr you can leave out the \"Only\" and have TESHA2 as a backup.\n"
                    },
                    {
                        "name": "Crypt::Random",
                        "content": "Requires Math::Pari which makes it unacceptable in some environments. Has more features (numbers\nin arbitrary bigint intervals or bit sizes). Crypt::Random::Seed is taking a simpler approach,\njust handling returning octets and letting upstream modules handle the rest.\n"
                    },
                    {
                        "name": "Data::Entropy",
                        "content": "An interesting module that contains a source encapsulation (defaults to system rand, but has\nmany plugins), a good CSPRNG (AES in counter mode), and the Data::Entropy::Algorithms module\nwith many ways to get bits, ints, bigints, floats, bigfloats, shuffles, and so forth. From my\nperspective, the algorithms module is the highlight, with a lot of interesting code.\n"
                    },
                    {
                        "name": "Upstream modules",
                        "content": "Some modules that could use this module to help them: Bytes::Random::Secure,\nMath::Random::ISAAC, Math::Random::Secure, and Math::Random::MT to name a few.\n"
                    }
                ]
            },
            "COPYRIGHT": {
                "content": "Copyright 2013 by Dana Jacobsen <dana@acm.org>\n\nThis program is free software; you can redistribute it and/or modify it under the same terms as\nPerl itself.\n\nThe software is provided \"AS IS\", without warranty of any kind, express or implied, including\nbut not limited to the warranties of merchantability, fitness for a particular purpose and\nnoninfringement. In no event shall the authors or copyright holders be liable for any claim,\ndamages or other liability, whether in an action of contract, tort or otherwise, arising from,\nout of or in connection with the software or the use or other dealings in the software.\n",
                "subsections": []
            }
        }
    }
}