liveBook · Manning

Crypt

As explained in Just Use Postgres!

crypt is a pgcrypto function that hashes a password with a salt and can reproduce a hash for password verification.

crypt is a pgcrypto function for hashing passwords with salts. Pair it with gen_salt('bf') when creating an account so identical passwords produce different stored hashes. section 7.2.2

A typical password workflow is:

  • Install pgcrypto with CREATE EXTENSION pgcrypto;. section 7.2.2
  • Store crypt('SuperSecret123', gen_salt('bf')) in the password_hash column. section 7.2.2
  • Verify a login by comparing password_hash with crypt('SuperSecret123', password_hash); crypt extracts the stored salt. section 7.2.2

Authenticate an account

SELECT username FROM accounts WHERE username = 'ahamilton' AND password_hash = crypt('SuperSecret123', password_hash); A matching password returns ahamilton. A misspelled password returns zero rows. section 7.2.2

Listing 7.3 Encrypting the password for a new user
INSERT INTO accounts (username, password_hash)
VALUES ('ahamilton', crypt('SuperSecret123', gen_salt('bf')));

Use the runnable insertion example to see crypt store a salted password hash. section 7.2.2

How Just Use Postgres! covers it

How deep it goes
Explains salted hashing, stored-salt reuse, successful matching, and failed authentication through executable SQL examples.
Examples
Uses an accounts table, a Blowfish salt, the ahamilton account, and matching or mismatching passwords.
What it assumes
Assumes PostgreSQL account data and teaches pgcrypto installation, salted storage, and verification from the workflow.
What you can do after
Apply it via PostgreSQL and pgcrypto to store password hashes and authenticate users.
How it connects
Connects pgcrypto, password hashing, salts, password verification, and user authentication.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Just Use Postgres!. The section links point to the parts of the book it draws on.