在nodejs代码中使用window.crypto

时间:2014-09-08 13:37:44

标签: javascript node.js cryptography

我正在尝试在nodejs脚本中使用window.crypto.getRandomValues方法。根据我的理解,当我在node:

中运行这样的简单代码时,没有window元素
var array = new Uint32Array(10);
window.crypto.getRandomValues(array);

这就是我收到此错误的原因:

ReferenceError: window is not defined

如何在我的代码中使用此方法?

由于

3 个答案:

答案 0 :(得分:8)

您可以使用内置的crypto模块。它同时提供crypto.randomBytes()crypto.pseudoRandomBytes()

但是应该注意的是,这些方法给你一个Buffer对象,你不能传入Uint32Array或者类似的,所以API有点不同。

答案 1 :(得分:4)

您可以使用与窗口元素相同的模块:get-random-values

安装它:

npm install get-random-values --save

使用它:

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

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

答案 2 :(得分:0)

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

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

这与浏览器中的几乎完全一样,只需在 webcrypto 的末尾添加 requrie('crypto');