简体   繁体   English

crypto.pbkdf2是异步的,我如何将其视为同步?

[英]crypto.pbkdf2 is asynchronous, how do I treat it as synchronous?

I'm using pbkdf2 in node.js for hashing passwords. 我在node.js中使用pbkdf2来进行散列密码。

My problem is that I'm responding to a request for authentication and I'm in the middle of authenticating if the passed credentials are correct. 我的问题是我正在响应身份验证请求,而我正在验证传递的凭据是否正确。 I'm presuming that pbkdf2 is async as it could potentially take a large amount of time (dependant on the size of the iterations). 我假设pbkdf2是异步的,因为它可能需要花费大量时间(取决于迭代的大小)。 However moving the remaining authentication logic into a separate method to utilise the callback seems a tad ugly. 然而,将剩余的身份验证逻辑移动到一个单独的方法来利用回调似乎有点难看。

Is there a better approach than either using a timer or throwing all the consecutive authentication logic into a separate function? 有没有比使用定时器或将所有连续的认证逻辑投入单独的函数更好的方法? I know most will say that I should use the callback, but in my use case this just doesn't make sense. 我知道大多数人会说我应该使用回调,但在我的用例中这没有意义。 I cannot continue authentication until I have applied pbkdf2 to the passed password. 在将pbkdf2应用于传递的密码之前,我无法继续身份验证。

According to the Node.js crypto docs , there is both an asynchronous and synchronous version of the PBKDF2 function. 根据Node.js加密文档 ,有一个PBKDF2函数的异步和同步版本。

crypto.pbkdf2(password, salt, iterations, keylen, callback) crypto.pbkdf2(密码,盐,迭代,keylen,回调)

Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive a key of given length from the given password, salt and iterations. 异步PBKDF2应用伪随机函数HMAC-SHA1从给定密码,salt和迭代中导出给定长度的密钥。 The callback gets two arguments (err, derivedKey) . 回调有两个参数(err, derivedKey)

crypto.pbkdf2Sync(password, salt, iterations, keylen) crypto.pbkdf2Sync(密码,盐,迭代,keylen)

Synchronous PBKDF2 function. 同步PBKDF2功能。 Returns derivedKey or throws error. 返回derivedKey或throws错误。

I can see two solutions for your problem. 我可以看到两个解决方案。

First one is to use some library to wrap asynchronous calls. 第一个是使用一些库来包装异步调用。 You may try node-sync or node-promise . 您可以尝试node-syncnode-promise node-sync is better suited for what you want. node-sync更适合您想要的。

Second solution is to use bcrypt instead of crypto: 第二种解决方案是使用bcrypt而不是crypto:

var bcrypt = require('bcrypt');
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync(password, salt);

bcrypt is a special library for password hashing in node. bcrypt是节点中用于密码散列的特殊库。 It's more secure then build-in crypto module and provides some useful methods like hashSync and compareSync . 它比内置加密模块更安全,并提供一些有用的方法,如hashSynccompareSync

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

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