Skip to content

Commit

Permalink
Improve crypto import
Browse files Browse the repository at this point in the history
  • Loading branch information
paulmillr committed Mar 15, 2023
1 parent 412a108 commit 71dfc9a
Show file tree
Hide file tree
Showing 5 changed files with 13 additions and 20 deletions.
6 changes: 4 additions & 2 deletions esm/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
{
"type": "module",
"browser": {
"crypto": false,
"./crypto": "./esm/cryptoBrowser.js"
"node:crypto": false
},
"node": {
"./crypto": "./esm/cryptoNode.js"
}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
},
"license": "MIT",
"browser": {
"crypto": false,
"node:crypto": false,
"./crypto": "./crypto.js"
},
"devDependencies": {
Expand Down
7 changes: 2 additions & 5 deletions src/crypto.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
// Global symbol available in browsers only, node.js 19+, deno and others
declare const globalThis: Record<string, any> | undefined;
export const crypto: { node?: any; web?: any } = {
node: undefined,
web: typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined,
};
export const crypto =
typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
9 changes: 3 additions & 6 deletions src/cryptoNode.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import * as nodeCrypto from 'crypto';

export const crypto: { node?: any; web?: any } = {
node: nodeCrypto,
web: undefined,
};
import * as nc from 'node:crypto';
export const crypto =
nc && typeof nc === 'object' && 'webcrypto' in nc ? (nc.webcrypto as any) : undefined;
9 changes: 3 additions & 6 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,11 +186,8 @@ export function wrapConstructorWithOpts<H extends Hash<H>, T extends Object>(
* Secure PRNG
*/
export function randomBytes(bytesLength = 32): Uint8Array {
if (crypto.web) {
return crypto.web.getRandomValues(new Uint8Array(bytesLength));
} else if (crypto.node) {
return new Uint8Array(crypto.node.randomBytes(bytesLength).buffer);
} else {
throw new Error("The environment doesn't have randomBytes function");
if (crypto && typeof crypto.getRandomValues === 'function') {
return crypto.getRandomValues(new Uint8Array(bytesLength));
}
throw new Error("The environment doesn't have randomBytes function");
}

0 comments on commit 71dfc9a

Please sign in to comment.