如何在nodejs中使用getRandomValues()?

Alb*_*ejo 3 arrays node.js

我正在使用 Javascript 生成wireguard 密钥对,但它是面向浏览器的,因此我删除了窗口对象,并且还有一个阻止创建私钥的问题。

问题是这行代码我无法在nodejs中运行:

    function generatePresharedKey() {

var privateKey = new Uint8Array(32);
var crypto = require('crypto');
crypto.getRandomValues(privateKey);

                return privateKey;
        }
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误

crypto.getRandomValues(privateKey);
       ^

TypeError: crypto.getRandomValues is not a function
Run Code Online (Sandbox Code Playgroud)

如果我尝试使用 require 调用 getRandomValues ,它会说找不到模块。 var getRandomValues = require('get-random-values');

我该如何导入它?npm install get-random-values 没有帮助。

有什么建议吗?

在这里小提琴:

    function generatePresharedKey() {

var privateKey = new Uint8Array(32);
var crypto = require('crypto');
crypto.getRandomValues(privateKey);

                return privateKey;
        }
Run Code Online (Sandbox Code Playgroud)

Law*_*one 5

类别:加密货币

\n
    \n
  • 添加于:v15.0.0
  • \n
\n
\n

调用 require(\'crypto\').webcrypto 返回 Crypto\n类的实例。Crypto 是一个单例,可提供对加密 API 其余部分的访问。

\n
\n

例子:

\n
const privateKey = new Uint8Array(32);\nconst webcrypto = require(\'crypto\').webcrypto;\nwebcrypto.getRandomValues(privateKey);\n
Run Code Online (Sandbox Code Playgroud)\n

结果:

\n

\xc3\xb7\xc3\x86VY{\xc3\xb1\xc3\x95\xc3\x93\xc2\xbb\xc3\x83V\xc3\xadA0\xc2\xb2\xe2\x80\xa0x\xc3\xb2\xc2\xa5x\xc2\xb4\xc3\xbc^18

\n