mongoose - 试图用 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() + "");
},
};
我知道这可能太多了,但是任何人都可以向我解释这些代码行在外行术语的加密中是如何工作的吗?如果有人能帮助像我这样的学生理解这一点,我将不胜感激..\
预先感谢!
解决方案
authenticate :调用此方法通过将用户提供的密码文本与存储在数据库中的特定用户的 hashed_password 匹配来验证登录尝试。
encryptPassword :此方法用于从纯文本密码生成加密哈希,并使用 Node.js 中的加密模块生成唯一的盐值。
makeSalt :此方法使用执行时的当前时间戳和 Math.random() 生成唯一且随机的盐值。
加密模块提供了一系列加密功能,包括一些标准的加密散列算法。在我们的代码中,我们使用 SHA1 散列算法和 createHmac from crypto 从密码文本和盐对生成加密 HMAC 散列。散列算法为相同的输入值生成相同的散列。但是为了确保两个用户在碰巧使用相同的密码文本时不会得到相同的哈希密码,我们在为每个用户生成哈希密码之前将每个密码与唯一的盐值配对。这也将使猜测正在使用的散列算法变得困难,因为相同的用户输入似乎生成了不同的散列。
推荐阅读
- java - Java 类转换规则
- javascript - Photoshop script to delete layer by name of multiple documents
- c# - updating a foreign key column in sql from C# using linq
- sql - MS Access simple SQL update query
- list - addition of numbers, in a list, that are smaller than a given number
- python - Can my Local Eclipse Install Access Libraries in Docker Container?
- php - 准备好的语句返回 false 但查询成功
- c++ - 如何将 100 次试验的结果输出到文本文件
- python - WSGI 应用程序工厂模式和导入时间创建的模块级对象
- python - 用递归函数替换简单的for循环?