# Storing Passwords Securely

**NEVER STORE PASSWORDS IN PLAIN TEXT!**

Storing plain text passwords in a database is a significant security risk. If a hacker gains access to the database, they will have access to all the passwords in plain text, which can lead to disastrous consequences. Even if the database is encrypted, storing plain text passwords is still a bad practice because the encryption key can be compromised, and the hacker can decrypt the passwords.

Additionally, users often reuse passwords across multiple accounts, and storing plain text passwords in a database can compromise not only the user's account on the current platform but also their other accounts that use the same password.

To mitigate these risks, it's best to use a one-way hashing algorithm to store passwords in the database. This way, even if the database is compromised, the hacker will not be able to retrieve the plain text passwords. Instead, they will only be able to compare the hashed values with their own guesses to try and crack them.

The time it takes to crack a hashed password depends on several factors, including the hashing algorithm used, the length and complexity of the password, and the computing power of the attacker. If a strong hashing algorithm, such as bcrypt or scrypt, is used with a sufficiently long and complex password, cracking the hash can take a very long time, ranging from several hours to several years or even decades.

#### Hashing Passwords in Flask

Flask is built on top of a package called Werkzeug which includes helper functions (`generate_password_hash` and `check_password_hash`) for dealing with hashed passwords.

**Hashing**

```python
from werkzeug.security import generate_password_hash, check_password_hash

# Store ONLY password_hash in the database (NOT the plain text password)
password = 'password1234'
password_hash = generate_password_hash(password)
```

**Checking Passwords Against the Hash**

```python
from werkzeug.security import generate_password_hash, check_password_hash

def some_flask_route():
    password = request.form.get('password')
    password_hash = sql_select('SELECT password_hash FROM users WHERE id=1')
    password_matches = check_password_hash(password_hash, password)

    if password_matches:
        # User typed the correct password
    else:
        # User typed the incorrect password
```
