NodeJS: bcrypt vs native crypto

柔情痞子 提交于 2020-04-29 04:29:08

问题


Can someone point out the differences between the two and example situations where use each?

bcrypt looks great.


回答1:


Use bcrypt where you want to do slow and computationally expensive hashing -- this will generally be for hashes where you really don't want an attacker to be able to reverse the hash, e.g. user passwords. Use native crypto for everything else.




回答2:


In companion with the @mike-scott's answer, you should prefer bcrypt for password related stuff but still you can use crypto for a wide range of tasks like create random tokens or a HMAC checksum or SHA1/MD5 hashes:

var crypto = require('crypto'); 

// random tokens
var buf = crypto.randomBytes(16).toString('hex');
console.log('Random token of %d bytes in hexadecimal: %s', buf.length, buf);
var buf = crypto.randomBytes(16).toString('base64');
console.log('Random token of %d bytes in base 64: %s', buf.length, buf);

// a hashed message authentication checksum (HMAC) using a shared secret key
var string = 'My coffee please';
var key = 'Right away sir';

var encrypted = crypto.createHmac('sha1', key).update(string).digest('hex');
console.log('Encrypting "%s" using passphrase "%s": %s', string, key, encrypted);

// a MD5 hash
var hashmd5 = crypto.createHash('md5').update(string).digest('hex');
console.log('The MD5 hash of "%s" is %s', string, hashmd5); 

// a SHA1 hash
var hashsha1 = crypto.createHash('sha1').update(string).digest('hex');
console.log('The SHA1 hash of "%s" is %s', string, hashsha1); 



回答3:


I would use nodejs's native crypto library

I think the decision should not be just based on who does what better, it is much more than that

You should know why node.js included an inbuilt module for crypto, while it was not originally part of node.js and many libraries were popular in npm repository, including bcrypt

The reason was, cryptography is an important security aspect, using an external module from npm has the possibility of malicious code injected, which defeats original security objective

Hence need a trusted library for such cryptographic function, which was the motivation for nodejs to provide such a library

If you think the cryptographic method is not strong, better raise issue on nodejs about same instead of blindly trusting an external library

Still don't believe me? read this article https://hackernoon.com/im-harvesting-credit-card-numbers-and-passwords-from-your-site-here-s-how-9a8cb347c5b5



来源:https://stackoverflow.com/questions/6951867/nodejs-bcrypt-vs-native-crypto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!