Skip to content

Commit 2875dbf

Browse files
authored
Merge pull request #206 from sergey-alekseev/master
Start calibration from the minimum cost supported by the algorithm
2 parents 011b67b + 27e1689 commit 2875dbf

4 files changed

Lines changed: 15 additions & 2 deletions

File tree

CHANGELOG

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,3 +92,4 @@
9292
- Update C and Java implementations to latest versions [GH #182 by @fonica]
9393
- Bump default cost to 12 [GH #181 by @bdewater]
9494
- Remove explicit support for Rubies 1.8 and 1.9
95+
- Start calibration from the minimum cost supported by the algorithm [GH #206 by @sergey-alekseev]

lib/bcrypt/engine.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ class Engine
55
DEFAULT_COST = 12
66
# The minimum cost supported by the algorithm.
77
MIN_COST = 4
8+
# The maximum cost supported by the algorithm.
9+
MAX_COST = 31
810
# Maximum possible size of bcrypt() salts.
911
MAX_SALT_LENGTH = 16
1012

@@ -99,7 +101,7 @@ def self.valid_secret?(secret)
99101
# # should take less than 1000ms
100102
# BCrypt::Password.create("woo", :cost => 12)
101103
def self.calibrate(upper_time_limit_in_ms)
102-
40.times do |i|
104+
(BCrypt::Engine::MIN_COST..BCrypt::Engine::MAX_COST-1).each do |i|
103105
start_time = Time.now
104106
Password.create("testing testing", :cost => i+1)
105107
end_time = Time.now - start_time

lib/bcrypt/password.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ class << self
4242
# @password = BCrypt::Password.create("my secret", :cost => 13)
4343
def create(secret, options = {})
4444
cost = options[:cost] || BCrypt::Engine.cost
45-
raise ArgumentError if cost > 31
45+
raise ArgumentError if cost > BCrypt::Engine::MAX_COST
4646
Password.new(BCrypt::Engine.hash_secret(secret, BCrypt::Engine.generate_salt(cost)))
4747
end
4848

spec/bcrypt/engine_spec.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,15 @@
11
require File.expand_path(File.join(File.dirname(__FILE__), "..", "spec_helper"))
22

3+
describe 'BCrypt::Engine' do
4+
describe '.calibrate(upper_time_limit_in_ms)' do
5+
context 'a tiny upper time limit provided' do
6+
it 'returns a minimum cost supported by the algorithm' do
7+
expect(BCrypt::Engine.calibrate(0.001)).to eq(4)
8+
end
9+
end
10+
end
11+
end
12+
313
describe "The BCrypt engine" do
414
specify "should calculate the optimal cost factor to fit in a specific time" do
515
first = BCrypt::Engine.calibrate(100)

0 commit comments

Comments
 (0)