Password Hashing With pgcrypto crypt

Hash passwords with pgcrypto crypt and gen_salt so every hash embeds its own salt, then verify candidates against the stored hash.

SqlSecurity Boundaries

Code

snippet
-- pgcrypto: crypt + gen_salt produce a self-salted hash, format $2a$12$<salt><digest>
CREATE EXTENSION IF NOT EXISTS pgcrypto;

CREATE TABLE app_users (
    user_id       int PRIMARY KEY,
    email         text NOT NULL UNIQUE,
    password_hash text NOT NULL
);

INSERT INTO app_users (user_id, email, password_hash)
VALUES (1, '[email protected]', crypt('correct-horse-battery', gen_salt('bf', 12)));

-- verification: crypt the candidate plaintext with the stored hash (it embeds the salt and rounds); equal output means the password is correct
SELECT email,
       crypt('correct-horse-battery', password_hash) = password_hash AS valid,
       crypt('wrong-guess', password_hash) = password_hash AS rejected
FROM app_users
WHERE email = '[email protected]';

How the snippet works

The file runs SELECT / INSERT / CREATE statements, touching app_users.

Mechanically, the statements are built from: a WHERE clause constraining which rows the statement operates on; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out.

Applying it

The app_users table is the working surface here.

Statements that matter

SELECT email,
       crypt('correct-horse-battery', password_hash) = password_hash AS valid,
       crypt('wrong-guess', password_hash) = password_hash AS rejected
FROM app_users
WHERE email = '[email protected]';
INSERT INTO app_users (user_id, email, password_hash)
VALUES (1, '[email protected]', crypt('correct-horse-battery', gen_salt('bf', 12)));
CREATE TABLE app_users (
    user_id       int PRIMARY KEY,
    email         text NOT NULL UNIQUE,
    password_hash text NOT NULL
);

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
`app_users`.