Ruby Logo

Secure Password Handling

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

Home Ruby Secure Password Handling

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.

Quick Navigation

Related Topics

Video Tutorial

Watch and learn secure password handling

Pro Tip: After reading through the content above, watch this video to reinforce your understanding and see the concepts in action!