哈希在环回中为同一密码生成不同的哈希值?

问题描述 投票:0回答:1

我正在将回送哈希器用作

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;
  }
}
typescript hash loopback loopback4
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.