1 | // Copyright (c) Jupyter Development Team.
|
2 | // Distributed under the terms of the Modified BSD License.
|
3 | /*-----------------------------------------------------------------------------
|
4 | | Copyright (c) 2014-2017, PhosphorJS Contributors
|
5 | |
|
6 | | Distributed under the terms of the BSD 3-Clause License.
|
7 | |
|
8 | | The full license is in the file LICENSE, distributed with this software.
|
9 | |----------------------------------------------------------------------------*/
|
10 |
|
11 | import { fallbackRandomValues } from './random';
|
12 |
|
13 | // Declare ambient variables for `window` and `require` to avoid a
|
14 | // hard dependency on both. This package must run on node.
|
15 | declare let require: any;
|
16 |
|
17 | /**
|
18 | * The namespace for random number related functionality.
|
19 | */
|
20 | export namespace Random {
|
21 | /**
|
22 | * A function which generates random bytes.
|
23 | *
|
24 | * @param buffer - The `Uint8Array` to fill with random bytes.
|
25 | *
|
26 | * #### Notes
|
27 | * A cryptographically strong random number generator will be used if
|
28 | * available. Otherwise, `Math.random` will be used as a fallback for
|
29 | * randomness.
|
30 | *
|
31 | * The following RNGs are supported, listed in order of precedence:
|
32 | * - `window.crypto.getRandomValues`
|
33 | * - `window.msCrypto.getRandomValues`
|
34 | * - `require('crypto').randomFillSync
|
35 | * - `require('crypto').randomBytes
|
36 | * - `Math.random`
|
37 | */
|
38 | export const getRandomValues = (() => {
|
39 | // Look up the crypto module if available.
|
40 | const crypto: any =
|
41 | (typeof require !== 'undefined' && require('crypto')) || null;
|
42 |
|
43 | // Node 7+
|
44 | if (crypto && typeof crypto.randomFillSync === 'function') {
|
45 | return function getRandomValues(buffer: Uint8Array): void {
|
46 | return crypto.randomFillSync(buffer);
|
47 | };
|
48 | }
|
49 |
|
50 | // Node 0.10+
|
51 | if (crypto && typeof crypto.randomBytes === 'function') {
|
52 | return function getRandomValues(buffer: Uint8Array): void {
|
53 | let bytes = crypto.randomBytes(buffer.length);
|
54 | for (let i = 0, n = bytes.length; i < n; ++i) {
|
55 | buffer[i] = bytes[i];
|
56 | }
|
57 | };
|
58 | }
|
59 |
|
60 | // Fallback
|
61 | return fallbackRandomValues;
|
62 | })();
|
63 | }
|
64 |
|
\ | No newline at end of file |