Spearfisher
Spearfisher

Reputation: 8783

Use window.crypto in nodejs code

I am trying to use the window.crypto.getRandomValues method in a nodejs script. From my understanding there is no window element when I run a simple code like this in node:

var array = new Uint32Array(10);
window.crypto.getRandomValues(array);

Which is why I get this error:

ReferenceError: window is not defined

How can I use this method in my code?

Thanks

Upvotes: 37

Views: 31213

Answers (7)

Censuradho
Censuradho

Reputation: 31

I had this problem too, I solved it this way

import * as crypto from 'node:crypto'

export function randomChar() {
  return crypto.webcrypto.getRandomValues(new BigUint64Array(1))[0].toString(36)
}

Reference: How to use getRandomValues() in nodejs?

Upvotes: 1

derpedy-doo
derpedy-doo

Reputation: 3108

As of Node.js v19.0.0 (noted in this changelog: https://github.com/nodejs/node/releases/tag/v19.0.0) globalThis.crypto in Node.js is now the same as webcrypto imported from 'crypto':

So you can now do this and get the same (random) result in Node.js as in the browser:

globalThis.crypto.getRandomValues

Note the usage of globalThis rather than window. See docs here if needed: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis

Upvotes: 2

user3064538
user3064538

Reputation:

In Node.js 19 you can just use it (without window.)

const array = new Uint32Array(10);
crypto.getRandomValues(array);

Upvotes: 0

Ray Foss
Ray Foss

Reputation: 3883

Here is how to use it in Node 16 with TypeScript. I'm hijacking the web types and overriding the @types/node type, which are missing webcrypto.

import { webcrypto } from 'crypto'
const crypto = webcrypto as unknown as Crypto
const random = crypto.getRandomValues(new Uint8Array(24))

This sandbox will work in Node 16, but stackblitz won't release node 16 for another couple months. https://stackblitz.com/edit/koa-starter-wychx9?file=package.json

Issue: github.com/denoland/node_deno_shims/issues/56

Upvotes: 2

Nitsua
Nitsua

Reputation: 275

const crypto = require('crypto').webcrypto;

let a = new Uint8Array(24);
console.log(crypto.getRandomValues(a));

This works almost exactly like the one in the browser, by adding webcrypto to the end of requrie('crypto');.

Upvotes: 24

Mohamed Mansour
Mohamed Mansour

Reputation: 40199

You can use this module which is the same as the window element: get-random-values

Install it:

npm install get-random-values --save

Use it:

var getRandomValues = require('get-random-values');

var array = new Uint32Array(10);
getRandomValues(array);

Upvotes: 11

mscdex
mscdex

Reputation: 106746

You can use the built-in crypto module instead. It provides both a crypto.randomBytes() as well as a crypto.pseudoRandomBytes().

However it should be noted that these methods give you a Buffer object, you cannot pass in a Uint32Array or similar, so the API is a bit different.

Upvotes: 21

Related Questions