Password hashing

suggest change

Never store passwords as plain text, and never store them encrypted either: if the key leaks, every password leaks with it. Store a password hash: a one-way value from which the password can't be recovered, but which lets you check a login attempt.

A good password hash has three properties:

In Ruby the usual choices are the bcrypt gem (the default in Rails), the argon2 gem (the current OWASP recommendation), or scrypt and PBKDF2 from the openssl standard library when you can't add a gem.

Why SHA-256 is not enough

General-purpose hash functions such as MD5, SHA-1 and SHA-256 are designed to be fast, which is exactly wrong for passwords:

require 'digest'
require 'benchmark'

n = 1_000_000
t = Benchmark.realtime { n.times { |i| Digest::SHA256.hexdigest("password#{i}") } }
puts "SHA-256: #{(n / t).round} hashes/second on one core"

puts Digest::SHA256.hexdigest("hunter2")
puts Digest::SHA256.hexdigest("hunter2")
SHA-256: 1406747 hashes/second on one core
f52fbd32b2b3b86ff88ef6c490628285f482af15ddcb29541f94bcf526a3f6c7
f52fbd32b2b3b86ff88ef6c490628285f482af15ddcb29541f94bcf526a3f6c7

That's 1.4 million guesses per second from interpreted Ruby on one core; a GPU does billions. And without a salt, equal passwords give equal hashes, so one cracked hash cracks every account that uses the same password. Adding a salt yourself (SHA256(salt + password)) fixes the second problem but not the first. Use an algorithm built for passwords.

bcrypt

Install the gem (it has a C extension, so you need a compiler on Linux and macOS):

$ gem install bcrypt

or in a Gemfile:

gem "bcrypt", "~> 3.1"

Hashing and verifying

require 'bcrypt'

hash = BCrypt::Password.create("correct horse battery staple")
puts hash
puts hash.class

# store hash.to_s in the database; later, on login:
stored = BCrypt::Password.new(hash.to_s)
p stored == "correct horse battery staple"
p stored == "Correct horse battery staple"
p stored.is_password?("correct horse battery staple")
$2a$12$.WtwJB/fHCbj5IaxZg1f8u5D/dDJwHBUvLhmgEpv61DP32b1xZCR2
BCrypt::Password
true
false
true

BCrypt::Password is a subclass of String, so you can save it straight into a string column (60 characters is enough). BCrypt::Password.new parses a stored hash, and its == is overridden: it hashes the candidate with the stored salt and cost and compares the results. is_password? is an alias that reads better.

The comparison only works one way round. stored == "password" calls BCrypt::Password#==; "password" == stored calls String#== and compares the plain text with the hash, which is always false.

Anatomy of a bcrypt hash

The salt and the settings are stored inside the hash string, so you don't need extra columns:

$2a$12$.WtwJB/fHCbj5IaxZg1f8u5D/dDJwHBUvLhmgEpv61DP32b1xZCR2
 \/ \/ \____________________/\_____________________________/
 |  |          salt                    checksum
 |  cost (2^12 rounds)
 version
require 'bcrypt'

h = BCrypt::Password.create("secret")
p h.version
p h.cost
p h.salt
p h.checksum

p BCrypt::Password.create("secret") == BCrypt::Password.create("secret")
"2a"
12
"$2a$12$.zFT9RLxm6up6mwOFrdh3."
"/7if1SAO64xo9thOF2GgOhm8FOv1BTa"
false

The last line compares two BCrypt::Password objects. Each create picks a new random salt, so hashing the same password twice gives different strings. That is why you must verify with == on a parsed hash and can't look users up by WHERE password_hash = ?.

Choosing the cost

The cost is a power of two: each step doubles the work. The default is 12 (BCrypt::Engine::DEFAULT_COST), the allowed range is 4 to 31:

require 'bcrypt'
require 'benchmark'

[10, 11, 12, 13, 14].each do |cost|
  t = Benchmark.realtime { BCrypt::Password.create("secret", cost: cost) }
  puts format("cost %2d: %6.0f ms", cost, t * 1000)
end
cost 10:     39 ms
cost 11:     75 ms
cost 12:    148 ms
cost 13:    304 ms
cost 14:    611 ms

Pick the highest cost that keeps a login under roughly 100-300 ms on your production servers. Remember that the hashing blocks a thread (or a Puma worker) for that long, so a very high cost also makes login an easy target for denial-of-service. BCrypt::Engine.calibrate(250) returns the cost that takes about 250 ms on the current machine.

In tests, hashing at cost 12 slows down every factory that creates a user. Lower it there:

# spec/spec_helper.rb or test/test_helper.rb
BCrypt::Engine.cost = BCrypt::Engine::MIN_COST

(Rails does this automatically in the test environment via ActiveModel::SecurePassword.min_cost.)

Invalid hashes

BCrypt::Password.new raises if the string isn't a bcrypt hash, for example a legacy MD5 value left in the column:

require 'bcrypt'

p BCrypt::Password.valid_hash?("$2a$12$L2KYfY8XgdMILxHo3G4suufI8JkLMrZebd/gvoLjlxrATSIHwrgxO")
p BCrypt::Password.valid_hash?("5f4dcc3b5aa765d61d8327deb882cf99")

begin
  BCrypt::Password.new("5f4dcc3b5aa765d61d8327deb882cf99")
rescue BCrypt::Errors::InvalidHash => e
  puts "#{e.class}: #{e.message}"
end
true
false
BCrypt::Errors::InvalidHash: invalid hash

The 72-byte limit

bcrypt only looks at the first 72 bytes of the password and silently ignores the rest:

require 'bcrypt'

a = "x" * 72
h = BCrypt::Password.create(a)
p h == a
p h == a + "anything else"
true
true

72 bytes is a lot for typed passwords, but it's only 18 characters of emoji or 24 of most Asian scripts (3 bytes each in UTF-8). Either reject passwords longer than 72 bytes at registration (Rails' has_secure_password does this) or use Argon2, which has no such limit.

Argon2

Argon2id won the Password Hashing Competition and is what OWASP recommends for new systems. Besides CPU time it uses a configurable amount of memory, which makes GPU and ASIC cracking much more expensive. The argon2 gem wraps the reference C implementation:

$ gem install argon2
require 'argon2'

hash = Argon2::Password.create("correct horse battery staple")
puts hash

p Argon2::Password.verify_password("correct horse battery staple", hash)
p Argon2::Password.verify_password("wrong", hash)
$argon2id$v=19$m=65536,t=3,p=4$jzIGEaMeIrTJnVVscn4imA$GXbYhc+3m/a6vubAD/cNot4IEnrCSOQo/UYd4gnPajk
true
false

As with bcrypt, the hash string is self-describing: the variant (argon2id), version, memory in KiB (m), number of passes (t), parallelism (p), salt and checksum, all base64-encoded and separated by $. The defaults are 64 MiB, 3 passes and 4 lanes.

Tuning the parameters

Create an Argon2::Password instance with your settings and reuse it. m_cost is the base-2 logarithm of the memory in KiB (16 means 2^16 KiB = 64 MiB):

require 'argon2'

hasher = Argon2::Password.new(t_cost: 2, m_cost: 16, p_cost: 1)  # 2 passes, 2**16 KiB = 64 MiB
hash = hasher.create("secret")
puts hash

info = Argon2::HashFormat.new(hash)
p [info.variant, info.version, info.t_cost, info.m_cost, info.p_cost]
$argon2id$v=19$m=65536,t=2,p=1$p9LTuQqP+hXIN92taP9flw$hmP9W43vbURjfpDdvyJ8uuoLHzKBIVtFPm2b2e+tnUI
["argon2id", 19, 2, 65536, 1]

OWASP's minimum is 19 MiB with 2 passes (m_cost: 15 is 32 MiB, the nearest power of two above it); the gem's defaults are comfortably above that. Every concurrent login allocates m of memory, so a server with 16 Puma threads doing logins at once needs 16 x 64 MiB = 1 GiB at peak. Size accordingly.

verify_password reads the parameters from the stored hash, so you can change the settings at any time: old hashes still verify with their old settings and new ones use the new settings.

A pepper (secret key)

A pepper is a secret mixed into every hash but stored outside the database, for example in an environment variable or a secrets manager. If an attacker steals only a database dump, they can't even start guessing. Argon2 supports this natively:

require 'argon2'

PEPPER = ENV.fetch("PASSWORD_PEPPER", "dev-only-pepper-6c1f0a")

hasher = Argon2::Password.new(secret: PEPPER)
hash = hasher.create("secret")

p Argon2::Password.verify_password("secret", hash, PEPPER)
p Argon2::Password.verify_password("secret", hash)                # no pepper
p Argon2::Password.verify_password("secret", hash, "wrong-pepper")
true
false
false

The pepper is defense in depth, not a replacement for a slow hash. The downside is that losing it invalidates every password, and rotating it requires users to log in again, so treat it like any other production secret.

Without a gem: scrypt and PBKDF2 from OpenSSL

The openssl standard library includes two password-hashing functions, OpenSSL::KDF.scrypt and OpenSSL::KDF.pbkdf2_hmac. They return raw key bytes, so you have to generate the salt and design a storage format yourself.

scrypt

scrypt is memory-hard like Argon2. Its parameters are N (CPU/memory cost, a power of two), r (block size) and p (parallelism); memory use is about 128 * N * r bytes:

require 'openssl'

module Scrypt
  N, R, P, LEN = 2**17, 8, 1, 32   # 128 MiB of memory (128 * N * r bytes)

  def self.create(password)
    salt = OpenSSL::Random.random_bytes(16)
    key  = OpenSSL::KDF.scrypt(password, salt: salt, N: N, r: R, p: P, length: LEN)
    "scrypt$#{N}$#{R}$#{P}$#{[salt].pack("m0")}$#{[key].pack("m0")}"
  end

  def self.verify(password, stored)
    _, n, r, p, salt, key = stored.split("$")
    salt = salt.unpack1("m0")
    key  = key.unpack1("m0")
    actual = OpenSSL::KDF.scrypt(password, salt: salt, N: n.to_i, r: r.to_i, p: p.to_i,
                                 length: key.bytesize)
    OpenSSL.fixed_length_secure_compare(actual, key)
  end
end

h = Scrypt.create("secret")
puts h
p Scrypt.verify("secret", h)
p Scrypt.verify("Secret", h)
scrypt$131072$8$1$X/8/FAWIPxpJ/auJqmU+xA==$IlKRz3RUjUKXuINjpKe6Pu1ogOuoZhEwQ7riDjZxHWY=
true
false

Points worth copying from this example:

PBKDF2

PBKDF2 is not memory-hard, so it's the weakest option here, but it's FIPS-approved and sometimes required for compliance. OWASP recommends 600,000 iterations with HMAC-SHA256:

require 'openssl'

salt = OpenSSL::Random.random_bytes(16)
key = OpenSSL::KDF.pbkdf2_hmac("secret", salt: salt, iterations: 600_000,
                               length: 32, hash: "sha256")
puts key.unpack1("H*")
6ed9d0451f27583a473c7b45baffd2dbeb3ce006a0cae15ceff0d0f151f1401f

Store the iteration count, salt and key in the same way as the scrypt example. Unless a rule forces scrypt or PBKDF2 on you, prefer the gems: a home-made format is one more thing to get wrong.

A complete login flow

Hashing is only part of the job. This in-memory store shows the other details that matter in a real application: case-insensitive emails, length checks, timing that doesn't reveal whether an account exists, and upgrading old hashes when users log in:

require 'bcrypt'

class UserStore
  COST = 12
  # Hashed once at boot; used when the email doesn't exist so that
  # "unknown user" takes as long as "wrong password".
  DUMMY_HASH = BCrypt::Password.create("dummy password", cost: COST)

  def initialize
    @users = {}   # email => password hash string (your DB column)
  end

  def register(email, password)
    raise ArgumentError, "password too short" if password.length < 8
    raise ArgumentError, "password too long"  if password.bytesize > 72
    @users[email.downcase] = BCrypt::Password.create(password, cost: COST).to_s
  end

  # Returns true/false. Upgrades old hashes on successful login.
  def authenticate(email, password)
    stored = @users[email.downcase]
    hash = stored ? BCrypt::Password.new(stored) : DUMMY_HASH
    ok = hash.is_password?(password)
    return false unless stored && ok

    if hash.cost < COST
      @users[email.downcase] = BCrypt::Password.create(password, cost: COST).to_s
      puts "  (rehashed #{email} from cost #{hash.cost} to #{COST})"
    end
    true
  end

  # for the demo: pretend an old account was created with a low cost
  def import_legacy(email, password, cost)
    @users[email.downcase] = BCrypt::Password.create(password, cost: cost).to_s
  end
end

store = UserStore.new
store.register("alice@example.com", "correct horse battery staple")
store.import_legacy("bob@example.com", "hunter2hunter2", 10)

p store.authenticate("alice@example.com", "correct horse battery staple")
p store.authenticate("ALICE@example.com", "wrong")
p store.authenticate("nobody@example.com", "whatever")
p store.authenticate("bob@example.com", "hunter2hunter2")
p store.authenticate("bob@example.com", "hunter2hunter2")
true
false
false
  (rehashed bob@example.com from cost 10 to 12)
true
true

Some notes on the design:

For Argon2 the "needs rehash" check compares the parameters stored in the hash with your current ones:

require 'argon2'

def upgrade_needed?(hash, t_cost:, m_cost:)
  info = Argon2::HashFormat.new(hash)
  info.variant != "argon2id" || info.t_cost < t_cost || info.m_cost < 2**m_cost
end

old = Argon2::Password.create("pw", t_cost: 2, m_cost: 15)
p upgrade_needed?(old, t_cost: 3, m_cost: 16)
cur = Argon2::Password.create("pw", t_cost: 3, m_cost: 16)
p upgrade_needed?(cur, t_cost: 3, m_cost: 16)
true
false

Normalizing Unicode passwords

The same visible password can be typed as different byte sequences. A user who registered on a Mac and logs in from Windows may send é as one code point or as e followed by a combining accent:

composed   = "caf\u00E9" # é as one code point
decomposed = "cafe\u0301" # e + combining acute accent
p composed == decomposed
p composed.unicode_normalize(:nfkc) == decomposed.unicode_normalize(:nfkc)
false
true

Hash functions see bytes, so these would be two different passwords. Normalizing with password.unicode_normalize(:nfkc) before both hashing and verifying avoids the problem (this is what NIST SP 800-63B suggests). Add it from the start: changing it later breaks existing hashes of non-ASCII passwords. Don't strip whitespace or change case; they are part of the password. See Unicode and encodings for more on normalization forms.

Rails: has_secure_password

In Rails you rarely call bcrypt directly. Add bcrypt to the Gemfile, add a password_digest string column, and call has_secure_password:

class User < ApplicationRecord
  has_secure_password
  normalizes :email, with: ->(e) { e.strip.downcase }
end

user = User.create!(email: "alice@example.com",
                    password: "correct horse battery staple",
                    password_confirmation: "correct horse battery staple")

user.password_digest     # => "$2a$12$..."
user.authenticate("correct horse battery staple")  # => user
user.authenticate("wrong")                         # => false

User.authenticate_by(email: "alice@example.com", password: "correct horse battery staple")
# => user, or nil

has_secure_password adds the virtual password and password_confirmation attributes, validates presence, confirmation and the 72-byte maximum, and hashes with BCrypt::Password.create. Prefer User.authenticate_by (Rails 7.1+) over User.find_by(email:)&.authenticate(...): it hashes even when no user matches, which is the dummy-hash protection from the previous section. Rails 8's bin/rails generate authentication builds a complete session-based login on top of this.

Summary

Option Where Memory-hard Notes
Argon2id argon2 gem yes first choice for new code, no length limit, built-in pepper
bcrypt bcrypt gem no Rails default, battle-tested, 72-byte limit
scrypt OpenSSL::KDF.scrypt yes no gem needed, you design the storage format
PBKDF2 OpenSSL::KDF.pbkdf2_hmac no for FIPS compliance, 600,000+ iterations
MD5, SHA-1, SHA-256 digest no never for passwords

Whatever you choose: use a per-user random salt (all the libraries above do this for you), store the parameters with the hash, compare in constant time, rehash on login when settings change, and keep the hashing out of logs and error reports. For tokens, JWTs and HTTP authentication see Authentication.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents