34

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

mscdex
  • 104,356
  • 15
  • 192
  • 153
Spearfisher
  • 8,445
  • 19
  • 70
  • 124

6 Answers6

21

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.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • ok thanks. How can I turn the buffer object returned as a simple 256-bit number? – Spearfisher Sep 08 '14 at 13:55
  • You'd have to use some javascript big number/integer library to convert the bytes to a number that large. – mscdex Sep 08 '14 at 14:05
  • 3
    Note that as of version 7.10.0 of Node, there is a [`crypto.randomFillSync()`](https://nodejs.org/docs/latest/api/crypto.html#crypto_crypto_randomfillsync_buffer_offset_size) function in NodeJS which allows you to pass a `TypedArray`. – Heretic Monkey Jun 05 '18 at 21:17
20
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');.

Smart Manoj
  • 5,230
  • 4
  • 34
  • 59
Nitsua
  • 235
  • 2
  • 8
11

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);
Mohamed Mansour
  • 39,445
  • 10
  • 116
  • 90
2

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

Ray Foss
  • 3,649
  • 3
  • 30
  • 31
0

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?

0

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

const array = new Uint32Array(10);
crypto.getRandomValues(array);
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103