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.
Code
-- 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
bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.Password Entropy EstimatorEstimate a password's alphabet size and Shannon entropy in bits, then translate that into offline crack times at realistic guessing rates.Password Strength MeterScore a password from 0 to 100 based on length and character classes, and get clear suggestions to make it stronger. Everything runs locally.
FAQ
- Which tables appear in this script?
- `app_users`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.