Class: Crypto
- Added in: v15.0.0
Calling require('crypto').webcrypto returns an instance of the Crypto class. Crypto is a singleton that provides access to the remainder of the crypto API.
Example:
const privateKey = new Uint8Array(32);
const webcrypto = require('crypto').webcrypto;
webcrypto.getRandomValues(privateKey);
Result:
÷ÆVY{ñÕÓ»ÃVíA0²†xò¥x´ü^18
Class: Crypto
- Added in: v15.0.0
Calling require('crypto').webcrypto returns an instance of the Crypto class. Crypto is a singleton that provides access to the remainder of the crypto API.
Example:
const privateKey = new Uint8Array(32);
const webcrypto = require('crypto').webcrypto;
webcrypto.getRandomValues(privateKey);
Result:
÷ÆVY{ñÕÓ»ÃVíA0²†xò¥x´ü^18
You need to understand getRandomValues is on window.crypto that means it works on browser. To make it work on Node.js you need to install get-random-values
npm i get-random-values
In your module add this:
const getRandomValues = require('get-random-values'),
array = new Uint8Array(10);
getRandomValues(array);
console.log(getRandomValues(array));
For all who is NodeJS and seeking for answer:
import * as crypto from 'crypto';
I ran into this same error in the command line: Uncaught TypeError: crypto.randomBytes is not a function
This did NOT work for me:
$ node
> require("crypto")
> crypto.randomBytes(32).toString("hex")
Crypto and randomBytes have to be called in the same command:
$ node
> require('crypto').randomBytes(32).toString('hex')
The output is something like this:
'7a3161b8c92dbf26f0717e89edd27bf10094d2f5cc0f4f2d70d08f463f2881db'
After a good bit of searching, I finally found the solution here: https://massimilianomarini.com/2020/04/random-string/
Use the following code to set up the crypto property globally. It will allow Jest to access
window.cryptoin the browser environmentglobal.cryptoin non-browsers environments. (Node/Typescript scripts).
It uses the globalThis which is now available on most of the latest browsers as well as Node.js 12+
const crypto = require('crypto');
Object.defineProperty(globalThis, 'crypto', {
value: {
getRandomValues: arr => crypto.randomBytes(arr.length)
}
});
Like @RwwL, the accepted answer did not work for me. I found that the polyfill used in this library did work: commit with polyfill
//setupTests.tsx
const nodeCrypto = require('crypto');
window.crypto = {
getRandomValues: function (buffer) {
return nodeCrypto.randomFillSync(buffer);
}
};
//jest.config.js
module.exports = {
//...
setupFilesAfterEnv: ["<rootDir>/src/setupTests.tsx"],
};