> For the complete documentation index, see [llms.txt](https://kinesis-school-of-programming.gitbook.io/nestjs-unleashed/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kinesis-school-of-programming.gitbook.io/nestjs-unleashed/extra-module-1-authentication-authorization/password-hashing/basic-solution.md).

# Basic solution

Let's first solve the problem, and after that improve the solution.

To be able to hash passwords, let's first install the package **bcrypt**.

```sh
yarn add bcrypt
yarn add -D @types/bcrypt
```

Now, going back to the <mark style="color:blue;">`UsersService`</mark>, let's create a private method to hash a <mark style="color:blue;">`password`</mark>.

```typescript
private async hashPassword(password: string) {
  const salt = await genSalt();
  return hash(password, salt);
}
```

{% hint style="info" %}
The <mark style="color:blue;">`salt`</mark> is a collection of random characters that are mixed with the <mark style="color:blue;">`password`</mark> before hashing it, making it harder for the original <mark style="color:blue;">`password`</mark> to be discovered.
{% endhint %}

> This [article](https://en.wikipedia.org/wiki/Salt_\(cryptography\)) (Wikipedia) further dicusses about this topic.

Now, in the <mark style="color:blue;">`create()`</mark> method, we can extract the <mark style="color:blue;">`password`</mark> from the DTO in order to hash it before saving the <mark style="color:blue;">`user`</mark>.

```typescript
const { password } = createUserDto;
const hashedPassword = await this.hashPassword(password);

const user = this.usersRepository.create({
  ...createUserDto,
  password: hashedPassword,
});
```

In the <mark style="color:blue;">`update()`</mark> method, it's the same thing. We just need to also check if the <mark style="color:blue;">`password`</mark> was indeed altered before attempting to hash it.

```typescript
const hashedPassword = password && (await this.hashPassword(password));
```

And we're done, we have password hashing working. Let's now improve the solution.

<mark style="color:green;">**Commit**</mark> - Implementing password hashing
