使用bcrypt和对象分配进行密码哈希

时间:2019-03-28 06:49:10

标签: javascript hash bcrypt assign salt

我需要将明文密码替换为散列密码。我正在使用bcryptjs来帮助我。

我曾尝试分配明确使用哈希密码的密码,但我的bash出现错误。

我要制作的代码:

const bcrypt = require('bcryptjs');
const students = require('./students1.json');
const fs = require('fs');

let secureUsers = [];
for (let student of students) {
    let salt = bcrypt.genSaltSync(10);
    let passHash = bcrypt.hashSync(student.password, salt);
    Object.assign(student.password, passHash);
    secureUsers.push(secStudent);
}
fs.writeFileSync('secStudents.json', JSON.stringify(secureUsers, null, 2));
console.log('wrote file!');

我得到的错误:

$ node bcryptExample.js
C:\Users\mziad\assignment-mziadeh1\servers\bcryptExample.js:13
    Object.assign(student.password, passHash);
           ^

TypeError: Cannot assign to read only property '0' of object '[object String]'
    at Function.assign (<anonymous>)
    at Object.<anonymous> (C:\Users\mziad\assignment-mziadeh1\servers\bcryptExample.js:13:12)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

我要哈希的示例:

{
    "netid": "ky4531",
    "firstName": "Frankie",
    "lastName": "Griffith",
    "email": "erasement1803@outlook.com",
    "password": "t'|x/)$g"
  },
  {
    "netid": "tw0199",
    "firstName": "Julietta",
    "lastName": "Vargas",
    "email": "ezekiel1960@outlook.com",
    "password": "Rc*pKe$w"
  }

我需要将密码与哈希码交换,因此为什么要尝试分配密码。但是我遇到了一个我不理解的错误,我现在无法真正发现我的代码有任何问题。

1 个答案:

答案 0 :(得分:1)

似乎您误解了Object.assign函数的工作方式。 Object.assign函数的作用是,它遍历源参数的每个属性(第一个参数之后的参数),并在第一个参数中覆盖它。

您的示例中的问题是您尝试使用String作为其参数Object.assign('abc', 'def')来调用Object.assign。 JavaScript中的字符串文字实际上是字符数组,而对象中的数组则以索引作为属性。默认情况下,无法重新分配字符串属性(索引)(可写:false)。

这是一个示范:

var a = 'abc';
console.log(a[0]) // outputs 'a'

var descriptor = Object.getOwnPropertyDescriptor(a, 0)
console.log(descriptor)
//outputs
/*
{ value: 'a',
  writable: false,
  enumerable: true,
  configurable: false }
*/

Object.assign('abc', 'def');// throws Cannot assign to read only property '0' of object '[object String]'

如您所见,可写设置为false,这意味着您无法重新分配字符串中的每个字符。这解释了为什么错误消息指出字符串'abc'的属性'0'无法分配新值。

因此解决方案是执行student.password = passHash而不是Object.assign(student.password, passHash);