ald*_*tis 41 security passwords cryptography password-hash node.js
我目前正在使用以下内容来加密密码:
var pass_shasum = crypto.createHash('sha256').update(req.body.password).digest('hex');
Run Code Online (Sandbox Code Playgroud)
您能否提出改进建议,使项目更安全?
bal*_*azs 87
我使用以下代码来加密和散列密码.
var bcrypt = require('bcrypt');
exports.cryptPassword = function(password, callback) {
bcrypt.genSalt(10, function(err, salt) {
if (err)
return callback(err);
bcrypt.hash(password, salt, function(err, hash) {
return callback(err, hash);
});
});
};
exports.comparePassword = function(plainPass, hashword, callback) {
bcrypt.compare(plainPass, hashword, function(err, isPasswordMatch) {
return err == null ?
callback(null, isPasswordMatch) :
callback(err);
});
};
Run Code Online (Sandbox Code Playgroud)
小智 6
bcrypt也可以同步调用。示例咖啡脚本:
bcrypt = require('bcrypt')
encryptionUtil =
encryptPassword: (password, salt) ->
salt ?= bcrypt.genSaltSync()
encryptedPassword = bcrypt.hashSync(password, salt)
{salt, encryptedPassword}
comparePassword: (password, salt, encryptedPasswordToCompareTo) ->
{encryptedPassword} = @encryptPassword(password, salt)
encryptedPassword == encryptedPasswordToCompareTo
module.exports = encryptionUtil
Run Code Online (Sandbox Code Playgroud)
使用打字稿进行 bcrypt
Run Code Online (Sandbox Code Playgroud)npm i bcrypt npm i -D @types/bcrypt
import * as bcrypt from 'bcrypt';
export const Encrypt = {
cryptPassword: (password: string) =>
bcrypt.genSalt(10)
.then((salt => bcrypt.hash(password, salt)))
.then(hash => hash),
comparePassword: (password: string, hashPassword: string) =>
bcrypt.compare(password, hashPassword)
.then(resp => resp)
}
Run Code Online (Sandbox Code Playgroud)
示例:加密
const myEncryptPassword = await Encrypt.cryptPassword(password);
Run Code Online (Sandbox Code Playgroud)
示例:比较
const myBoolean = await Encrypt.comparePassword(password, passwordHash);
Run Code Online (Sandbox Code Playgroud)