Sobes.tech
Junior — Middle

How is storing and protecting user passwords implemented in PostgreSQL database?

sobes.tech AI

Answer from AI

In PostgreSQL, user passwords are usually not stored in plain text in the database. Instead, hashing and salting are used to protect passwords.

Main approaches:

  • At the application level: the user's password is hashed (for example, using bcrypt, Argon2, or PBKDF2) with a unique salt, and only the hash is stored in the database.
  • At the PostgreSQL level: the database management system uses its own mechanism for user authentication, where passwords are stored as hashes (MD5 or SCRAM-SHA-256).

Example of storing a password in a user table:

CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  username TEXT UNIQUE NOT NULL,
  password_hash TEXT NOT NULL
);

During registration in the application:

const bcrypt = require('bcrypt');
const password = 'user_password';
const saltRounds = 10;
const hash = await bcrypt.hash(password, saltRounds);
// save hash in the password_hash field

Thus, even if the database is compromised, the actual user passwords remain protected.