我正在寻找一些关于如何使用node安全存储密码和其他敏感数据的示例.js和mongodb.

我希望所有东西都使用一种独特的盐,我会将其存储在mongo文档中的哈希旁边.

对于身份验证,我是否只需要对输入进行加密并将其与存储的哈希匹配?

我需要解密这些数据吗?如果需要,我应该怎么做?

私钥,甚至盐析方法是如何安全地存储在服务器上的?

我听说AES和河豚都是不错的 Select ,我应该用什么?

Any examples of how to design this would be wonderfully helpful!

谢谢

推荐答案

使用这个:https://github.com/ncb000gt/node.bcrypt.js/

bcrypt是关注这个用例的少数算法之一.您永远不能解密密码,只能验证用户输入的明文密码是否与存储/加密的哈希匹配.

bcrypt的使用非常简单.下面是我的Mongoose用户模式(CoffeeScript)的一个片段.请确保使用异步函数,因为bycrypt速度很慢(故意).

class User extends SharedUser
  defaults: _.extend {domainId: null}, SharedUser::defaults

  #Irrelevant bits trimmed...

  password: (cleartext, confirm, callback) ->
    errorInfo = new errors.InvalidData()
    if cleartext != confirm
      errorInfo.message = 'please type the same password twice'
      errorInfo.errors.confirmPassword = 'must match the password'
      return callback errorInfo
    message = min4 cleartext
    if message
      errorInfo.message = message
      errorInfo.errors.password = message
      return callback errorInfo
    self = this
    bcrypt.gen_salt 10, (error, salt)->
      if error
        errorInfo = new errors.InternalError error.message
        return callback errorInfo
      bcrypt.encrypt cleartext, salt, (error, hash)->
        if error
          errorInfo = new errors.InternalError error.message
          return callback errorInfo
        self.attributes.bcryptedPassword = hash
        return callback()

  verifyPassword: (cleartext, callback) ->
    bcrypt.compare cleartext, @attributes.bcryptedPassword, (error, result)->
      if error
        return callback(new errors.InternalError(error.message))
      callback null, result

此外,阅读this article, which should convince you that bcrypt is a good choice,帮助你避免变得"精力充沛".

Node.js相关问答推荐

利用Gemini:通过Vertex AI还是通过Google/generative-ai?

@nuxtjs/站点 map 错误提示:找不到包';NitroPack';

Stripe webhook无法访问Express请求原始正文

Node.js PNG缓冲区获取未知图像格式错误

当 Got 包因错误 JSON 崩溃时如何获取响应文本?

使用 Nodejs 获取 Firebase 云消息传递历史记录

等待不在 Express.js 中处理 res.app.render

try 在 NodeJS 项目中实现 SimplePay (OTP) 支付网关,但我无法获得与技术文档中相同的签名

如何找到特定文档并更新数组中特定键的值?

npm chokidar 触发事件两次

将 AllowDiskUse true 添加到 node.js 中的 MongoDB 聚合?

在 Express.js 中迭代子文档数组

使用 Node.js 在 MongoDB 中搜索

如何在拦截器中发送不同的请求?

eslint - vscode 的可选链接错误

Mongodb v4.0 Transaction, MongoError: Transaction numbers are allowed on a replica set member or mongos

Sequelize 基于关联的查找

User.findOrCreate 函数是做什么的,什么时候在Passport 中调用它?

当进程被杀死时,如何优雅地关闭我的 Express 服务器?

处理快速异步中间件中的错误