25

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
  • 99,783
  • 13
  • 184
  • 147
Spearfisher
  • 7,879
  • 18
  • 64
  • 119

4 Answers4

20

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
  • 99,783
  • 13
  • 184
  • 147
  • 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
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
  • 38,137
  • 10
  • 113
  • 89
8
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
  • 4,375
  • 4
  • 27
  • 51
Wolfy
  • 113
  • 1
  • 6
1

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,175
  • 3
  • 25
  • 26