Sobes.tech
Junior — Middle

How is the secure storage of passwords in a database implemented?

sobes.tech AI

Answer from AI

Secure storage of passwords in a database is achieved through hashing using cryptographically secure algorithms and adding salt (random salt). The essence is that the password is not stored in plain text, but its hash is stored, which cannot be reversed back to the original password.

Main steps:

  1. A unique random salt is generated for each password.
  2. A hash function, such as bcrypt, Argon2, or PBKDF2, is applied to the password and salt.
  3. The hash and salt (or just the hash if the algorithm manages the salt itself) are stored in the database.

Example in Python using the bcrypt library:

import bcrypt

password = b"mysecretpassword"
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(password, salt)

# hashed can be stored in the database

# Password verification:
entered_password = b"mysecretpassword"
if bcrypt.checkpw(entered_password, hashed):
    print("Password is correct")
else:
    print("Incorrect password")

Using specialized algorithms with salt protects against brute-force attacks and rainbow table attacks.

How is the secure storage of passwords in a database… - sobes.tech