-
Notifications
You must be signed in to change notification settings - Fork 35
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Use crypto.getRandomValues for both Node and browsers
Removes Node/browser-specific PRNGs, since crypto.getRandomValues is now available in Node.
- Loading branch information
Showing
3 changed files
with
11 additions
and
109 deletions.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |