Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- UserSchema.pre('save', function(next) {
- var user = this;
- var salt = crypto.randomBytes(128).toString('base64');
- crypto.pbkdf2(user.password, salt, 10000, 512, function(err, derivedKey) {
- user.password = derivedKey;
- next();
- });
- });
- UserSchema.methods.validPassword = function(password) {
- // need to salt and hash this password I think to compare
- // how to I get the salt?
- }
- function hashPassword(password) {
- var salt = crypto.randomBytes(128).toString('base64');
- var iterations = 10000;
- var hash = pbkdf2(password, salt, iterations);
- return {
- salt: salt,
- hash: hash,
- iterations: iterations
- };
- }
- function isPasswordCorrect(savedHash, savedSalt, savedIterations, passwordAttempt) {
- return savedHash == pbkdf2(passwordAttempt, savedSalt, savedIterations);
- }
- var bcrypt = require('bcrypt');
- var salt = bcrypt.genSaltSync(10);
- var hash = bcrypt.hashSync("B4c0//", salt);
- // Store hash in your password DB.
- // Load hash from your password DB.
- bcrypt.compareSync("B4c0//", hash); // true
- bcrypt.compareSync("not_bacon", hash); // false
- import * as crypto from 'crypto';
- const PASSWORD_LENGTH = 256;
- const SALT_LENGTH = 64;
- const ITERATIONS = 10000;
- const DIGEST = 'sha256';
- const BYTE_TO_STRING_ENCODING = 'hex'; // this could be base64, for instance
- /**
- * The information about the password that is stored in the database
- */
- interface PersistedPassword {
- salt: string;
- hash: string;
- iterations: number;
- }
- /**
- * Generates a PersistedPassword given the password provided by the user. This should be called when creating a user
- * or redefining the password
- */
- export async function generateHashPassword(password: string): Promise<PersistedPassword> {
- return new Promise<PersistedPassword>((accept, reject) => {
- const salt = crypto.randomBytes(SALT_LENGTH).toString(BYTE_TO_STRING_ENCODING);
- crypto.pbkdf2(password, salt, ITERATIONS, PASSWORD_LENGTH, DIGEST, (error, hash) => {
- if (error) {
- reject(error);
- } else {
- accept({
- salt,
- hash: hash.toString(BYTE_TO_STRING_ENCODING),
- iterations: ITERATIONS,
- });
- }
- });
- });
- }
- /**
- * Verifies the attempted password against the password information saved in the database. This should be called when
- * the user tries to log in.
- */
- export async function verifyPassword(persistedPassword: PersistedPassword, passwordAttempt: string): Promise<boolean> {
- return new Promise<boolean>((accept, reject) => {
- crypto.pbkdf2(passwordAttempt, persistedPassword.salt, persistedPassword.iterations, PASSWORD_LENGTH, DIGEST, (error, hash) => {
- if (error) {
- reject(error);
- } else {
- accept(persistedPassword.hash === hash.toString(BYTE_TO_STRING_ENCODING));
- }
- });
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement