From 27e168927a10d0028366fe364c1aafe1b62a25b4 Mon Sep 17 00:00:00 2001 From: Sergey Alekseev Date: Fri, 5 Jul 2019 21:00:31 +0300 Subject: [PATCH] start calibration from the minimum cost supported by the algorithm --- CHANGELOG | 1 + lib/bcrypt/engine.rb | 4 +++- lib/bcrypt/password.rb | 2 +- spec/bcrypt/engine_spec.rb | 10 ++++++++++ 4 files changed, 15 insertions(+), 2 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 8bead60..2f14add 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -92,3 +92,4 @@ - Update C and Java implementations to latest versions [GH #182 by @fonica] - Bump default cost to 12 [GH #181 by @bdewater] - Remove explicit support for Rubies 1.8 and 1.9 + - Start calibration from the minimum cost supported by the algorithm [GH #206 by @sergey-alekseev] diff --git a/lib/bcrypt/engine.rb b/lib/bcrypt/engine.rb index 226d142..2204843 100644 --- a/lib/bcrypt/engine.rb +++ b/lib/bcrypt/engine.rb @@ -5,6 +5,8 @@ class Engine DEFAULT_COST = 12 # The minimum cost supported by the algorithm. MIN_COST = 4 + # The maximum cost supported by the algorithm. + MAX_COST = 31 # Maximum possible size of bcrypt() salts. MAX_SALT_LENGTH = 16 @@ -99,7 +101,7 @@ def self.valid_secret?(secret) # # should take less than 1000ms # BCrypt::Password.create("woo", :cost => 12) def self.calibrate(upper_time_limit_in_ms) - 40.times do |i| + (BCrypt::Engine::MIN_COST..BCrypt::Engine::MAX_COST-1).each do |i| start_time = Time.now Password.create("testing testing", :cost => i+1) end_time = Time.now - start_time diff --git a/lib/bcrypt/password.rb b/lib/bcrypt/password.rb index 509a8d9..f984e32 100644 --- a/lib/bcrypt/password.rb +++ b/lib/bcrypt/password.rb @@ -42,7 +42,7 @@ class << self # @password = BCrypt::Password.create("my secret", :cost => 13) def create(secret, options = {}) cost = options[:cost] || BCrypt::Engine.cost - raise ArgumentError if cost > 31 + raise ArgumentError if cost > BCrypt::Engine::MAX_COST Password.new(BCrypt::Engine.hash_secret(secret, BCrypt::Engine.generate_salt(cost))) end diff --git a/spec/bcrypt/engine_spec.rb b/spec/bcrypt/engine_spec.rb index cde842c..90a681e 100644 --- a/spec/bcrypt/engine_spec.rb +++ b/spec/bcrypt/engine_spec.rb @@ -1,5 +1,15 @@ require File.expand_path(File.join(File.dirname(__FILE__), "..", "spec_helper")) +describe 'BCrypt::Engine' do + describe '.calibrate(upper_time_limit_in_ms)' do + context 'a tiny upper time limit provided' do + it 'returns a minimum cost supported by the algorithm' do + expect(BCrypt::Engine.calibrate(0.001)).to eq(4) + end + end + end +end + describe "The BCrypt engine" do specify "should calculate the optimal cost factor to fit in a specific time" do first = BCrypt::Engine.calibrate(100)