Skip to content

Commit

Permalink
Use crypto.getRandomValues for both Node and browsers
Browse files Browse the repository at this point in the history
Removes Node/browser-specific PRNGs, since
crypto.getRandomValues is now available in Node.
  • Loading branch information
dchest committed Jun 29, 2024
1 parent 5243520 commit 4a78f52
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 109 deletions.
36 changes: 0 additions & 36 deletions packages/random/source/browser.ts

This file was deleted.

52 changes: 0 additions & 52 deletions packages/random/source/node.ts

This file was deleted.

32 changes: 11 additions & 21 deletions packages/random/source/system.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,29 @@
// Copyright (C) 2016 Dmitry Chestnykh
// Copyright (C) 2024 Dmitry Chestnykh
// MIT License. See LICENSE file for details.

import { RandomSource } from "./";
import { BrowserRandomSource } from "./browser";
import { NodeRandomSource } from "./node";

const QUOTA = 65536;

export class SystemRandomSource implements RandomSource {
isAvailable = false;
name = "";
private _source: RandomSource;
isInstantiated = false;

constructor() {
// Try browser.
this._source = new BrowserRandomSource();
if (this._source.isAvailable) {
this.isAvailable = true;
this.name = "Browser";
return;
}

// If no browser source, try Node.
this._source = new NodeRandomSource();
if (this._source.isAvailable) {
if (crypto !== undefined && 'getRandomValues' in crypto) {
this.isAvailable = true;
this.name = "Node";
return;
this.isInstantiated = true;
}

// No sources, we're out of options.
}

randomBytes(length: number): Uint8Array {
if (!this.isAvailable) {
throw new Error("System random byte generator is not available.");
}
return this._source.randomBytes(length);
const out = new Uint8Array(length);
for (let i = 0; i < out.length; i += QUOTA) {
crypto.getRandomValues(out.subarray(i, i + Math.min(out.length - i, QUOTA)));
}
return out;
}
}

0 comments on commit 4a78f52

Please sign in to comment.