Secure Password Handling

Use bcrypt, salts, and password policies to store credentials safely.

Beginner 1 min read

Secure Password Handling

Never store plaintext passwords. Leverage established libraries (BCrypt) and enforce policies so account credentials remain protected even if databases leak.

Password hashing with BCrypt

require 'bcrypt' class User < ApplicationRecord include BCrypt def password=(new_password) self.password_digest = Password.create(new_password, cost: BCrypt::Engine.cost) end def authenticate(candidate) Password.new(password_digest) == candidate end end

Rails’ `has_secure_password` handles this boilerplate. Adjust BCrypt cost factors cautiously; higher cost means more CPU per hash, but better resistance to brute-force attacks.

Operational best practices

  • Enforce minimum password length (12+ characters) and encourage passphrases.
  • Rate-limit login attempts and account recovery flows; log suspicious behaviour.
  • Store secrets (pepper, salt) in environment variables or managed secret stores.
  • Rotate credentials and invalidate sessions promptly after password updates.