PS C:\Users\zchen\Programming\node-crypto-examples-main\src> node salt.js
{
email: 'bob@gmail.com',
password: '5b0caa7a0764e99a1ca2472e72e8cf5c:87d3f6b38f2ce30423bdaf9bc1dfe80329fce6c5ff061d040a8d59f369ba49178022833abdf1c88debb4b133ba085724a0379fcf608889395401e058c7c044cd'
}
login success!
login fail!
PS C:\Users\zchen\Programming\node-crypto-examples-main\src>
//salt.js
const { scryptSync, randomBytes, timingSafeEqual } = require('crypto');
const users = []
function signup(email, password) {
const salt = randomBytes(16).toString('hex');
const hashedPassword = scryptSync(password, salt, 64).toString('hex');
const user = { email, password: `${salt}:${hashedPassword}` }
users.push(user);
return user
}
function login(email, password) {
const user = users.find(v => v.email === email);
const [salt, key] = user.password.split(':');
const hashedBuffer = scryptSync(password, salt, 64);
const keyBuffer = Buffer.from(key, 'hex');
const match = timingSafeEqual(hashedBuffer, keyBuffer);
if (match) {
return 'login success!'
} else {
return 'login fail!'
}
}
const newUser = signup('bob@gmail.com', '12345')
console.log(newUser)
const try1 = login('bob@gmail.com', '12345')
console.log(try1)
const try2 = login('bob@gmail.com', '123')
console.log(try2)
reference:
No comments:
Post a Comment