简体   繁体   English

如何在节点js中同步crypto模块的crypto.randomBytes()函数?

[英]How do I synchronise crypto.randomBytes() function of crypto module in node js?

crypto = require('crypto')
async function generateToken(){
  await crypto.randomBytes(256,function(ex, buffer) {
    if (ex) {
      console.log("error generating token");
    }

        var token =  crypto
          .createHash('sha1')
          .update(buffer)
          .digest('hex');

        console.log(token);



  }
)}
console.log("before token");
generateToken();
console.log("after token");

In the above code, I wanted to synchronize the generateToken() method.在上面的代码中,我想同步generateToken()方法。 So I added async and await to the function, but I'm not getting the expected output which is所以我在函数中添加了asyncawait ,但我没有得到预期的输出

before token 
7f4f27037cd7dd65bd03d7e2fe859e608b9eebe2
after token 

the output I'm getting is我得到的输出是

before token 
after token
7f4f27037cd7dd65bd03d7e2fe859e608b9eebe2

What am I doing wrong in the above code?我在上面的代码中做错了什么?

edit: the following code would work but it is not synchronized.编辑:以下代码可以工作,但不同步。

crypto = require("crypto");
function generateToken() {
  return new Promise((resolve, reject) => {
    crypto.randomBytes(256, function(ex, buffer) {
      if (ex) {
        reject("error generating token");
      }
      const token = crypto
        .createHash("sha1")
        .update(buffer)
        .digest("hex");
      resolve(token);
    });
  });


  console.log(token);
}

console.log("before token");
generateToken().then((token) => {
  console.log(token);
  console.log("after token");
});
const crypto = require("crypto");
async function generateToken() {
  const buffer = await new Promise((resolve, reject) => {
    crypto.randomBytes(256, function(ex, buffer) {
      if (ex) {
        reject("error generating token");
      }
      resolve(buffer);
    });
  });
  const token = crypto
    .createHash("sha1")
    .update(buffer)
    .digest("hex");

  console.log(token);
  return token;
}

console.log("before token");
generateToken().then(token => {
  console.log("after token", token);
});

You can also call it in other async function您也可以在其他异步函数中调用它

async function otherFunction() {
  try {
    console.log("before token");
    const token = await generateToken();
    console.log("after token", token);
  } catch (e) {
    console.error(e)
  }
}

If you don't specify a function, then a synchronous version of the function is used and it returns the resulting bytes.如果未指定函数,则使用该函数的同步版本并返回结果字节。

token = crypto.randomBytes(256)

That way you don't need any kind of synchronization (everything is a callback, even when called promises, wait, async, whatnot... so synchronous code in an asynchronous world requires each previous callback to start the next asynchronous job, which can be annoying in some simple cases like this one.)这样你就不需要任何类型的同步(一切都是回调,即使调用 promises、wait、async 等等......所以异步世界中的同步代码需要每个先前的回调来启动下一个异步作业,这可以在像这样的一些简单情况下会很烦人。)

this is working fine...这工作正常......

 crypto = require("crypto");

    function generateToken() {
      return new Promise((resolve, reject) => {
        crypto.randomBytes(256, function(ex, buffer) {
          if (ex) {
            reject();
          }
          const token = crypto
            .createHash("sha1")
            .update(buffer)
            .digest("hex");
          console.log(token);
          resolve();
        });
      });

    }

    async function otherFunction() {
      try {
        console.log("before token");
        await generateToken()
        console.log("after token");
      } catch (e) {
        console.error(e)
      }
    }
    otherFunction();

The following method works with TypeScript "typescript": "^3.4.4"以下方法适用于 TypeScript "typescript": "^3.4.4"

const randomKey = async (length: Number) => {
  const buffer = await crypto.randomBytes(16);
  return buffer.toString("hex");
};

const getAndLogKey = async () => {
  const randomKey = await randomKey(16);
  console.log(randomKey);
};

should work with JS too也应该与 JS 一起工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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