我已经尝试了数天在我的Windows机器上安装bcrypt,但没有成功。其中一个依赖项(Windows 7 SDK)无论我如何尝试网络上的各种建议都不愿意安装。
我需要一个没有任何依赖关系的良好的bcrypt替代方案。
我已经尝试了数天在我的Windows机器上安装bcrypt,但没有成功。其中一个依赖项(Windows 7 SDK)无论我如何尝试网络上的各种建议都不愿意安装。
我需要一个没有任何依赖关系的良好的bcrypt替代方案。
查看 https://npmjs.org/package/bcryptjs,它完全兼容bcrypt但不需要依赖项。
或者使用https://npmjs.org/package/simplecrypt,如果您不想要加密模板,只需加密和解密字符串即可。
截至2020年4月24日,在crypto
模块中有一种很好的内置方法可以使用scrypt
来进行密码哈希处理。
// Using the built in crypto module
const { scryptSync, randomBytes } = require("crypto");
// Any random string here (ideally should be atleast 16 bytes)
const salt = randomBytes(16).toString("hex")
// Pass the password string and get hashed password back
// ( and store only the hashed string along with the salt in your database)
// {hashedPassword}${salt}
const getHash = (password) => scryptSync(password, salt, 32).toString("hex");
这里是 @malik-bagwala 的改进版本,增加了 JsDocs、类型和匹配密码函数。
import { randomBytes, scryptSync } from 'crypto';
// Pass the password string and get hashed password back
// ( and store only the hashed string in your database)
const encryptPassword = (password: string, salt: string) => {
return scryptSync(password, salt, 32).toString('hex');
};
/**
* Hash password with random salt
* @return {string} password hash followed by salt
* XXXX till 64 XXXX till 32
*
*/
export const hashPassword = (password: string): string => {
// Any random string here (ideally should be at least 16 bytes)
const salt = randomBytes(16).toString('hex');
return encryptPassword(password, salt) + salt;
};
// fetch the user from your db and then use this function
/**
* Match password against the stored hash
*/
export const matchPassword = (password: string, hash: string): Boolean => {
// extract salt from the hashed string
// our hex password length is 32*2 = 64
const salt = hash.slice(64);
const originalPassHash = hash.slice(0, 64);
const currentPassHash = encryptPassword(password, salt);
return originalPassHash === currentPassHash;
};
crypto.timingSafeEqual
代替originalPassHash === currentPassHash
来比较两个哈希值,以防止时序攻击。您可以在此SO答案中找到一个实现。 - Advenavalue1 === value2
是一个问题,而value1Hashed === value2Hashed
是一种原始的时间安全比较。这里有一篇文章介绍了这个问题:双 HMAC 比较(注意:我知道密码哈希 != HMAC;然而,两者都使用哈希算法)。 - undefined30% 的减速
可能会很烦人。 - Nux在编写加密代码时,你应该使用内置的加密模块。它基本上是 OpenSSL 的绑定,是一个快速、稳定、安全且经过充分验证的加密库。尝试实现自己的加密算法(或使用其他人未经验证的加密算法)会导致灾难。
如果你想要加密数据,只需调用 crypto.createCipher
,它将返回一个可读/可写的 Stream
。将数据写入流中,它将发出带有加密数据的数据事件。
例如:
var stream = crypto.createCipher('aes192', 'mysecretpassword');
stream.on('data', function(enc) {
// enc is a `Buffer` with a chunk of encrypted data
});
stream.write('some secret data');
stream.end();
可以使用Argon2i、Argon2d或Argon2id(默认)进行哈希,并验证密码是否与哈希匹配。
https://www.npmjs.com/package/argon2
const password = 'password123';
async function hashPassword(password) {
try {
const hashedPassword = await argon2.hash(password);
console.log('Hashed password:', hashedPassword);
} catch (error) {
console.error('Error hashing password:', error);
}
}
hashPassword(password);