Research
Security News
Threat Actor Exposes Playbook for Exploiting npm to Build Blockchain-Powered Botnets
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
seedrandom
Advanced tools
The seedrandom npm package is a library that allows developers to create seeded random number generators. This means that the random numbers generated can be repeatable and predictable if the same seed is used. It is useful for scenarios where reproducibility is important, such as in testing or simulations.
Basic Seeded Random Number Generation
This feature allows you to create a new random number generator that is seeded with a specific string. The same seed will produce the same sequence of numbers each time.
var seedrandom = require('seedrandom');
var rng = seedrandom('hello.');
console.log(rng());
Using Different Algorithms
Seedrandom supports different algorithms for random number generation, such as 'xor128', 'tychei', among others. This allows for flexibility in the properties of the random number sequence.
var seedrandom = require('seedrandom');
var rng = seedrandom('hello.', { algorithm: 'xor128' });
console.log(rng());
State Saving and Restoring
This feature allows you to save the state of the random number generator and create a new generator with that state, effectively cloning the generator at a specific point in its sequence.
var seedrandom = require('seedrandom');
var rng = seedrandom('hello.');
var state = rng.state();
var rng2 = seedrandom(state);
console.log(rng2());
Autoseeding
If no seed is provided, seedrandom can automatically generate a seed based on entropy from the current time and the execution environment, producing a unique random number sequence.
var seedrandom = require('seedrandom');
var rng = seedrandom();
console.log(rng());
random-js is a mathematically correct random number generator library for JavaScript. It provides a variety of distributions and utilities for generating random values. It is similar to seedrandom but offers a wider range of random generation methods and distributions.
mersenne-twister is a package that implements the Mersenne Twister algorithm for generating random numbers. It is known for its long period and high-quality random numbers. It is similar to seedrandom in that it can be seeded, but it uses a specific algorithm known for its statistical properties.
alea is a small, fast, and reliable random number generator. It is similar to seedrandom in that it can be seeded to produce repeatable sequences of random numbers. However, it uses a different algorithm and focuses on being compact and fast.
Seeded random number generator for JavaScript.
Version 3.0.5
Author: David Bau
Date: 2019-09-14
Can be used as a plain script, a Node.js module or an AMD module.
<script src="//cdnjs.cloudflare.com/ajax/libs/seedrandom/3.0.5/seedrandom.min.js">
</script>
// Make a predictable pseudorandom number generator.
var myrng = new Math.seedrandom('hello.');
console.log(myrng()); // Always 0.9282578795792454
console.log(myrng()); // Always 0.3752569768646784
// Use "quick" to get only 32 bits of randomness in a float.
console.log(myrng.quick()); // Always 0.7316977467853576
// Use "int32" to get a 32 bit (signed) integer
console.log(myrng.int32()); // Always 1966374204
// Calling seedrandom with no arguments creates an ARC4-based PRNG
// that is autoseeded using the current time, dom state, and other
// accumulated local entropy.
var prng = new Math.seedrandom();
console.log(prng()); // Reasonably unpredictable.
// Seeds using the given explicit seed mixed with accumulated entropy.
prng = new Math.seedrandom('added entropy.', { entropy: true });
console.log(prng()); // As unpredictable as added entropy.
// Warning: if you call Math.seedrandom without `new`, it replaces
// Math.random with the predictable new Math.seedrandom(...), as follows:
Math.seedrandom('hello.');
console.log(Math.random()); // Always 0.9282578795792454
console.log(Math.random()); // Always 0.3752569768646784
Note: calling Math.seedrandom('constant')
without new
will make
Math.random()
predictable globally, which is intended to be useful for
derandomizing code for testing, but should not be done in a production library.
If you need a local seeded PRNG, use myrng = new Math.seedrandom('seed')
instead. For example, cryptico,
an RSA encryption package, uses the wrong form,
and thus secretly makes Math.random()
perfectly predictable.
The cryptico library (and any other library that does this)
should not be trusted in a security-sensitive application.
The package includes some other fast PRNGs. To use Johannes Baagøe's extremely fast Alea PRNG:
<script src="//cdnjs.cloudflare.com/ajax/libs/seedrandom/3.0.5/lib/alea.min.js">
</script>
// Use alea for Johannes Baagøe's clever and fast floating-point RNG.
var arng = new alea('hello.');
// By default provides 32 bits of randomness in a float.
console.log(arng()); // Always 0.4783254903741181
// Use "double" to get 56 bits of randomness.
console.log(arng.double()); // Always 0.8297006866124559
// Use "int32" to get a 32 bit (signed) integer.
console.log(arng.int32()); // Always 1076136327
Besides alea, there are several other faster PRNGs available. Note that none of these fast PRNGs provide autoseeding: you need to provide your own seed (or use the default autoseeded seedrandom to make a seed).
PRNG name | Time vs native | Period | Author |
---|---|---|---|
alea | 1.95 ns, 0.9x | ~2^116 | Baagøe |
xor128 | 2.04 ns, 0.9x | 2^128-1 | Marsaglia |
tychei | 2.32 ns, 1.1x | ~2^127 | Neves/Araujo (ChaCha) |
xorwow | 2.40 ns, 1.1x | 2^192-2^32 | Marsaglia |
xor4096 | 2.40 ns, 1.1x | 2^4096-2^32 | Brent (xorgens) |
xorshift7 | 2.64 ns, 1.3x | 2^256-1 | Panneton/L'ecuyer |
quick | 3.80 ns, 1.8x | ~2^1600 | Bau (ARC4) |
(Timings were done on node v0.12.2 on a single-core Google Compute Engine
instance. quick
is just the 32-bit version of the RC4-based PRNG
originally packaged with seedrandom.)
npm install seedrandom
// Local PRNG: does not affect Math.random.
var seedrandom = require('seedrandom');
var rng = seedrandom('hello.');
console.log(rng()); // Always 0.9282578795792454
// Global PRNG: set Math.random.
seedrandom('hello.', { global: true });
console.log(Math.random()); // Always 0.9282578795792454
// Autoseeded ARC4-based PRNG.
rng = seedrandom();
console.log(rng()); // Reasonably unpredictable.
// Mixing accumulated entropy.
rng = seedrandom('added entropy.', { entropy: true });
console.log(rng()); // As unpredictable as added entropy.
// Using alternate algorithms, as listed above.
var rng2 = seedrandom.xor4096('hello.')
console.log(rng2());
Starting in version 3, when using via require('seedrandom'), the global
Math.seedrandom
is no longer available.
Similar to Node.js usage:
bower install seedrandom
require(['seedrandom'], function(seedrandom) {
var rng = seedrandom('hello.');
console.log(rng()); // Always 0.9282578795792454
});
<script src=//cdnjs.cloudflare.com/ajax/libs/seedrandom/3.0.5/seedrandom.min.js>
</script>
<!-- Seeds using urandom bits from a server. -->
<script src=//jsonlib.appspot.com/urandom?callback=Math.seedrandom>
</script>
<!-- Seeds mixing in random.org bits -->
<script>
(function(x, u, s){
try {
// Make a synchronous request to random.org.
x.open('GET', u, false);
x.send();
s = unescape(x.response.trim().replace(/^|\s/g, '%'));
} finally {
// Seed with the response, or autoseed on failure.
Math.seedrandom(s, !!s);
}
})(new XMLHttpRequest, 'https://www.random.org/integers/' +
'?num=256&min=0&max=255&col=1&base=16&format=plain&rnd=new');
</script>
var seed = Math.seedrandom(); // Use prng with an automatic seed.
document.write(Math.random()); // Pretty much unpredictable x.
var rng = new Math.seedrandom(seed); // A new prng with the same seed.
document.write(rng()); // Repeat the 'unpredictable' x.
function reseed(event, count) { // Define a custom entropy collector.
var t = [];
function w(e) {
t.push([e.pageX, e.pageY, +new Date]);
if (t.length < count) { return; }
document.removeEventListener(event, w);
Math.seedrandom(t, { entropy: true });
}
document.addEventListener(event, w);
}
reseed('mousemove', 100); // Reseed after 100 mouse moves.
The "pass" option can be used to get both the prng and the seed. The following returns both an autoseeded prng and the seed as an object, without mutating Math.random:
var obj = Math.seedrandom(null, { pass: function(prng, seed) {
return { random: prng, seed: seed };
}});
var seedrandom = Math.seedrandom;
var saveable = seedrandom("secret-seed", {state: true});
for (var j = 0; j < 1e5; ++j) saveable();
var saved = saveable.state();
var replica = seedrandom("", {state: saved});
assert(replica() == saveable());
In normal use the prng is opaque and its internal state cannot be accessed. However, if the "state" option is specified, the prng gets a state() method that returns a plain object the can be used to reconstruct a prng later in the same state (by passing that saved object back as the state option).
The random number sequence is the same as version 1.0 for string seeds.
The standard ARC4 key scheduler cycles short keys, which means that seedrandom('ab') is equivalent to seedrandom('abab') and 'ababab'. Therefore it is a good idea to add a terminator to avoid trivial equivalences on short string seeds, e.g., Math.seedrandom(str + '\0'). Starting with version 2.0, a terminator is added automatically for non-string seeds, so seeding with the number 111 is the same as seeding with '111\0'.
When seedrandom() is called with zero args or a null seed, it uses a seed drawn from the browser crypto object if present. If there is no crypto support, seedrandom() uses the current time, the native rng, and a walk of several DOM objects to collect a few bits of entropy.
Each time the one- or two-argument forms of seedrandom are called, entropy from the passed seed is accumulated in a pool to help generate future seeds for the zero- and two-argument forms of seedrandom.
On speed - This javascript implementation of Math.random() is several times slower than the built-in Math.random() because it is not native code, but that is typically fast enough. Some details (timings on Chrome 25 on a 2010 vintage macbook):
Autoseeding without crypto is somewhat slow, about 20-30 milliseconds on a 2012 windows 7 1.5ghz i5 laptop, as seen on Firefox 19, IE 10, and Opera. Seeded rng calls themselves are fast across these browsers, with slowest numbers on Opera at about 0.0005 ms per seeded Math.random().
Copyright 2019 David Bau.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
FAQs
Seeded random number generator for Javascript.
The npm package seedrandom receives a total of 2,200,162 weekly downloads. As such, seedrandom popularity was classified as popular.
We found that seedrandom demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
Security News
NVD’s backlog surpasses 20,000 CVEs as analysis slows and NIST announces new system updates to address ongoing delays.
Security News
Research
A malicious npm package disguised as a WhatsApp client is exploiting authentication flows with a remote kill switch to exfiltrate data and destroy files.