Commit 2a84f0e01db71967573b42cc2e730d867c1ce555
Merge pull request #63 from tjschuck/make_cost_globally_changeable_externally
Allow a default cost to be set externallyAman Gupta committed on 5/3/2013, 11:56:00 PM
Parent: 46157399e458e54e7c4186d3dbb88ac29fd3299c
Parent: f07a154d197c91c995590fabb5ae6d5f3f48ae97
Files changed
lib/bcrypt.rb | changed |
spec/bcrypt/password_spec.rb | changed |
lib/bcrypt.rb | ||
---|---|---|
@@ -35,8 +35,13 @@ | ||
35 | 35 | private_class_method :__bc_salt |
36 | 36 | private_class_method :__bc_crypt |
37 | 37 | end |
38 | 38 | |
39 | + class << self | |
40 | + attr_accessor :cost | |
41 | + end | |
42 | + self.cost = DEFAULT_COST | |
43 | + | |
39 | 44 | # Given a secret and a valid salt (see BCrypt::Engine.generate_salt) calculates |
40 | 45 | # a bcrypt() password hash. |
41 | 46 | def self.hash_secret(secret, salt, cost = nil) |
42 | 47 | if valid_secret?(secret) |
@@ -58,9 +63,9 @@ | ||
58 | 63 | end |
59 | 64 | end |
60 | 65 | |
61 | 66 | # Generates a random salt with a given computational cost. |
62 | - def self.generate_salt(cost = DEFAULT_COST) | |
67 | + def self.generate_salt(cost = self.cost) | |
63 | 68 | cost = cost.to_i |
64 | 69 | if cost > 0 |
65 | 70 | if cost < MIN_COST |
66 | 71 | cost = MIN_COST |
@@ -154,9 +159,9 @@ | ||
154 | 159 | # Example: |
155 | 160 | # |
156 | 161 | # @password = BCrypt::Password.create("my secret", :cost => 13) |
157 | 162 | def create(secret, options = {}) |
158 | - cost = options[:cost] || BCrypt::Engine::DEFAULT_COST | |
163 | + cost = options[:cost] || BCrypt::Engine.cost | |
159 | 164 | raise ArgumentError if cost > 31 |
160 | 165 | Password.new(BCrypt::Engine.hash_secret(secret, BCrypt::Engine.generate_salt(cost), cost)) |
161 | 166 | end |
162 | 167 |
spec/bcrypt/password_spec.rb | ||
---|---|---|
@@ -47,8 +47,17 @@ | ||
47 | 47 | specify "the cost should be set to the default if empty hash" do |
48 | 48 | BCrypt::Password.create("hello", {}).cost.should equal(BCrypt::Engine::DEFAULT_COST) |
49 | 49 | end |
50 | 50 | |
51 | + specify "the cost should be set to the passed value if provided" do | |
52 | + BCrypt::Password.create("hello", :cost => 5).cost.should equal(5) | |
53 | + end | |
54 | + | |
55 | + specify "the cost should be set to the global value if set" do | |
56 | + BCrypt::Engine.cost = 5 | |
57 | + BCrypt::Password.create("hello").cost.should equal(5) | |
58 | + end | |
59 | + | |
51 | 60 | specify "should read the version, cost, salt, and hash" do |
52 | 61 | password = BCrypt::Password.new(@hash) |
53 | 62 | password.version.should eql("2a") |
54 | 63 | password.cost.should equal(5) |
Built with git-ssb-web