-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
browser-random.ts
47 lines (38 loc) · 1.35 KB
/
browser-random.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"use strict";
import { arrayify } from "@ethersproject/bytes";
import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
const logger = new Logger(version);
// Debugging line for testing browser lib in node
//const window = { crypto: { getRandomValues: () => { } } };
let anyGlobal: any = null;
try {
anyGlobal = (window as any);
if (anyGlobal == null) { throw new Error("try next"); }
} catch (error) {
try {
anyGlobal = (global as any);
if (anyGlobal == null) { throw new Error("try next"); }
} catch (error) {
anyGlobal = { };
}
}
let crypto: any = anyGlobal.crypto || anyGlobal.msCrypto;
if (!crypto || !crypto.getRandomValues) {
logger.warn("WARNING: Missing strong random number source");
crypto = {
getRandomValues: function(buffer: Uint8Array): Uint8Array {
return logger.throwError("no secure random source avaialble", Logger.errors.UNSUPPORTED_OPERATION, {
operation: "crypto.getRandomValues"
});
}
};
}
export function randomBytes(length: number): Uint8Array {
if (length <= 0 || length > 1024 || (length % 1) || length != length) {
logger.throwArgumentError("invalid length", "length", length);
}
const result = new Uint8Array(length);
crypto.getRandomValues(result);
return arrayify(result);
};