Using bcrypt-ruby in Rails

What is bcrypt?

bcrypt Versions

  1. 3.1.18 — May 16, 2022 java (69.5 KB)
  2. 3.1.18 — May 16, 2022 (54.5 KB)
  3. 3.1.17 — March 14, 2022 java (69.5 KB)
  4. 3.1.17 — March 14, 2022 (54.5 KB)
  5. 3.1.16 — September 03, 2020 java (68.5 KB)
  6. 3.1.12 — May 16, 2018 (43.5 KB)

Development Dependencies :

How to install the bcrypt gem

gem install bcrypt

How bcrypt works

require 'bcrypt'
=> true
pw1 = BCrypt::Password.create("mypassword")
=> "$2a$12$5scgl6wb3P7eeaOniiendeHX4N1JMoRFSQ6AF9gEB.vii/pWk.LJi"
pw1.salt
=> "$2a$12$5scgl6wb3P7eeaOniiende"
pw1.checksum
=> "HX4N1JMoRFSQ6AF9gEB.vii/pWk.LJi"
BCrypt::Engine.cost = 8
=> 8
pw2 = BCrypt::Password.create("mypassword")
=> "$2a$08$uTUc7IHwjUrV7mCmNcb9OexGzgTOsLDunrZp04yd.DKEd2W37UUmG"
pw2.cost
=> 8

Configuring Ruby on Rails to use bcrypt

create_table “users”, do |t|
t.string “username”
t.string “password_digest”
end
class User < ApplicationRecord
has_secure_password
end
user = User.new(username: 'joe', password: '', password_confirmation: 'nomatch')
user.save
# => false, password required

user.password = 'mUc3m00RsqyRe'
user.save
# => false, confirmation doesn't match

user.password_confirmation = 'mUc3m00RsqyRe'
user.save
# => true

user.recovery_password = "42password"
user.recovery_password_digest
# =>”"$2a$04$iOfhwahFymCs5weB3BNH/uXkTG65HR.qpW.bNhEjFP3ftli3o5DQC"

user.save
# => true

user.authenticate('notright')
# => false

user.authenticate('mUc3m00RsqyRe')
# => user

user.authenticate_recovery_password('42password')
# => user

User.find_by(name: 'joe')&.authenticate('notright')
# => false

User.find_by(name: 'joe')&.authenticate('mUc3m00RsqyRe')
# => user

Create a user account

class UsersController < ApplicationController

def create
user = User.create(params[:user, :password, :password_confirmation])
end

end

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store