Skip to content

Commit e316d40

Browse files
committed
simplify ancient class Random
Node.js 20 implements the WebCrypto API. globalThis has existed since Node.js 12.
1 parent 433a4f8 commit e316d40

File tree

1 file changed

+3
-20
lines changed

1 file changed

+3
-20
lines changed

packages/crypto/src/random.ts

Lines changed: 3 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,10 @@
1-
declare const window: any;
2-
declare const self: any;
3-
41
export class Random {
52
/**
63
* Returns `count` cryptographically secure random bytes
74
*/
85
public static getBytes(count: number): Uint8Array {
9-
try {
10-
const globalObject = typeof window === "object" ? window : self;
11-
const cryptoApi =
12-
typeof globalObject.crypto !== "undefined" ? globalObject.crypto : globalObject.msCrypto;
13-
14-
const out = new Uint8Array(count);
15-
cryptoApi.getRandomValues(out);
16-
return out;
17-
} catch {
18-
try {
19-
// eslint-disable-next-line @typescript-eslint/no-var-requires
20-
const crypto = require("crypto");
21-
return new Uint8Array([...crypto.randomBytes(count)]);
22-
} catch {
23-
throw new Error("No secure random number generator found");
24-
}
25-
}
6+
const out = new Uint8Array(count);
7+
globalThis.crypto.getRandomValues(out);
8+
return out;
269
}
2710
}

0 commit comments

Comments
 (0)