Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails has_secure_password change BCrypt cost factor (aka work factor)

When using has_secure password in rails, how can I change the default cost factor BCrypt uses when creating the password digests?

I'd like to do this because the default cost factor used -- 10 -- is apparently a bit low (this post recommends setting it to 12 at least).

like image 455
Peter Berg Avatar asked Jan 21 '14 17:01

Peter Berg


People also ask

What is bcrypt cost factor?

Bcrypt Cost Factor = 6 + (Number years of user membership or some factor thereof) with an optional ceiling for total cost, perhaps modified in some way by the login frequency of that user.

How does bcrypt work in Rails?

bcrypt provides a password-hashing algorithm that allows us to add secure authentication to our Rails sites. A hash algorithm takes data (in this case, a password) and hashes it using an algorithm. A password hash combines a user's password with a piece of random data known as salt.

How expensive is bcrypt?

The default cost value of Laminas\Crypt\Password\Bcrypt is 10, requiring around 0.07s using a CPU Intel i5 at 3.3Ghz (the cost parameter is a relative value according to the speed of the CPU used).


1 Answers

This can be accomplished by putting the following code in your config file (e.g. production.rb, development.rb, test.rb, application.rb, etc.)

require 'bcrypt'
BCrypt::Engine::DEFAULT_COST = 12

Note that you can check your password digests to see what cost factor was used when encrypting them. E.g. in

$2a$12$k50jCqk8Bijj.wYxg69QBOg.t4VNMj/VmSkPCfeWWoOW

the cost factor is 12 the number immediately following the second $

like image 176
Peter Berg Avatar answered Oct 05 '22 12:10

Peter Berg