简体   繁体   中英

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

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.

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);
const crypto = require('crypto').webcrypto;

let a = new Uint8Array(24);
console.log(btoa(String.fromCharCode.apply(null, a)));

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

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))

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM