0

我正在使用环回哈希作为

import { PasswordHasher } from './hash.password.bcryptjs';

这有一个函数生成哈希

credentials.password = await this.passwordHasher.hashPassword(credentials.password);

我正在输入pass@1010生成哈希的密码,但它每次都会生成不同的哈希。但是相同字符串的哈希应该是相同的。

类代码

import { genSalt, hash } from 'bcryptjs';
import { compare } from 'bcryptjs';
import { inject } from '@loopback/core';
import { PasswordHasherBindings } from '../keys';

/**
 * Service HashPassword using module 'bcryptjs'.
 * It takes in a plain password, generates a salt with given
 * round and returns the hashed password as a string
 */
export type HashPassword = (
  password: string,
  rounds: number,
) => Promise<string>;
// bind function to `services.bcryptjs.HashPassword`
export async function hashPassword(
  password: string,
  rounds: number,
): Promise<string> {
  const salt = await genSalt(rounds);
  return await hash(password, salt);
}

export interface PasswordHasher<T = string> {
  hashPassword(password: T): Promise<T>;
  comparePassword(providedPass: T, storedPass: T): Promise<boolean>;
}

export class BcryptHasher implements PasswordHasher<string> {
  constructor(
    @inject(PasswordHasherBindings.ROUNDS)
    private readonly rounds: number,
  ) { }

  async hashPassword(password: string): Promise<string> {
    const salt = await genSalt(10);
    return await hash(password, salt);
  }

  async comparePassword(
    providedPass: string,
    storedPass: string,
  ): Promise<boolean> {
    const passwordIsMatched = await compare(providedPass, storedPass);
    return passwordIsMatched;
  }
}
4

1 回答 1

0

问题是您对每个哈希都使用了新的盐。如果你想获得稳定的哈希,你需要生成一次盐,然后在下一轮重新使用它。

于 2019-11-22T06:50:59.520 回答