首页 > 解决方案 > 试图用 Mongoose 理解 userSchema 密码加密

问题描述

我是一个完整的初学者,我跑到我老师的代码那里,我们首先尝试加密密码,然后最终将其保存到数据库中。

这是userSchema之后的代码:

userSchema
  .virtual("password")
  .set(function (password) {
    // create a temporary variable called _password
    this._password = password;
    // generate salt
    this.salt = this.makeSalt();
    // encryptPassword
    this.hashed_password = this.encryptPassword(password);
  })
  .get(function () {
    return this._password;
  });

userSchema.methods = {
  authenticate: function (plainText) {
    return this.encryptPassword(plainText) == this.hashed_password;
  },

  encryptPassword: function (password) {
    if (!password) return "";
    try {
      return crypto.createHmac("sha1", this.salt).update(password).digest("hex");
    } catch (err) {
      return "";
    }
  },

  makeSalt: function () {
    return Math.round(new Date().valueOf() * Math.random() + "");
  },
};

我知道这可能太多了,但是任何人都可以向我解释这些代码行在外行术语的加密中是如何工作的吗?如果有人能帮助像我这样的学生理解这一点,我将不胜感激..\

预先感谢!

标签: mongoosecryptojs

解决方案


authenticate :调用此方法通过将用户提供的密码文本与存储在数据库中的特定用户的 hashed_pa​​ssword 匹配来验证登录尝试。

encryptPassword :此方法用于从纯文本密码生成加密哈希,并使用 Node.js 中的加密模块生成唯一的盐值。

makeSalt :此方法使用执行时的当前时间戳和 Math.random() 生成唯一且随机的盐值。

加密模块提供了一系列加密功能,包括一些标准的加密散列算法。在我们的代码中,我们使用 SHA1 散列算法和 createHmac from crypto 从密码文本和盐对生成加密 HMAC 散列。散列算法为相同的输入值生成相同的散列。但是为了确保两个用户在碰巧使用相同的密码文本时不会得到相同的哈希密码,我们在为每个用户生成哈希密码之前将每个密码与唯一的盐值配对。这也将使猜测正在使用的散列算法变得困难,因为相同的用户输入似乎生成了不同的散列。


推荐阅读