# Protecting credential database against exploitation

## Salting and related concepts

:::{wpd} Hash function
A function that can be used to map data to fixed-size values.
:::

:::{wpd} Rainbow table
A precomputed table is a precomputed table for caching the outputs of a cryptographic hash function, usually for cracking password hashes
:::

:::{wpd} Salt
:id: Salt (cryptography)
Random data fed as an additional input to a one-way function that hashes a password or ... 
:::

Salting:
- prevents precomputed attacks like rainbow tables, so that the attackers must crack each password individually
- ensures that identical passwords have different hashes

But:
- it does not prevent brute-force attacks against individual passwords, so weak passwords like *password123* can be relatively quickly found.


## Salting in user registration
```{mermaid}
graph TD
st1(Start user registration) -->
a[Ask user password for registration] -->
b[Generate a random salt] -->
c[Combine password + salt] -->
d[Hash password + salt] -->
e[Store in database] -->
end1(end)
```

## Salting in user login

```{mermaid}
graph TD
st2(Start user login) -->
f[Ask user password for login] -->
g[Get user's salt and hash from the database] -->
h[Calculate hash of user-provided pass + salt] -->
check{{hash_user == hash_database}} -->
j[Allow login] -->
end2(end)

check -->|false| f
```

## Salting example code

The following code is from the [system login interface project](system-login-demo):

:::{literalinclude} /code-wi/SystemLogin/Models.cs
:language: cs
:linenos:
:::

:::{activity} Analyzing password salting in code
The code above salts the password.
1. Where does salting take place?
1. There are two different `Hash` functions. One of them returns *salt and salted password hash*, and the other one only *salted password hash*. What is the reason?
:::

## Used resources

- [.NET cryptography model – Choose an algorithm](https://learn.microsoft.com/en-us/dotnet/standard/security/cryptography-model#choose-an-algorithm)
  - [Rfc2898DeriveBytes.Pbkdf2 Method](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.rfc2898derivebytes.pbkdf2) 
  - [RandomNumberGenerator.GetBytes Method](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getbytes)
- [PBKDF2](https://en.wikipedia.org/wiki/PBKDF2)
  - [NIST 800-132 – Section 5.1 The Salt](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf#%5B%7B%22num%22%3A18%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22XYZ%22%7D%2C90%2C482%2Cnull%5D)