git ssb

0+

dangerousbeans / %aPBe2k3ugtjBr4rrsU1…



Tree: 697b93db79cf10dcb480e9260337517ae93d75dc

Files: 697b93db79cf10dcb480e9260337517ae93d75dc / lib / bcrypt.rb

6440 bytesRaw
1# A wrapper for OpenBSD's bcrypt/crypt_blowfish password-hashing algorithm.
2
3if RUBY_PLATFORM == "java"
4 require 'java'
5else
6 require "openssl"
7end
8
9if RUBY_ENGINE == "maglev"
10 require 'bcrypt_engine'
11else
12 require 'bcrypt_ext'
13end
14
15# A Ruby library implementing OpenBSD's bcrypt()/crypt_blowfish algorithm for
16# hashing passwords.
17module BCrypt
18 module Errors
19 class InvalidSalt < StandardError; end # The salt parameter provided to bcrypt() is invalid.
20 class InvalidHash < StandardError; end # The hash parameter provided to bcrypt() is invalid.
21 class InvalidCost < StandardError; end # The cost parameter provided to bcrypt() is invalid.
22 class InvalidSecret < StandardError; end # The secret parameter provided to bcrypt() is invalid.
23 end
24
25 # A Ruby wrapper for the bcrypt() C extension calls and the Java calls.
26 class Engine
27 # The default computational expense parameter.
28 DEFAULT_COST = 10
29 # The minimum cost supported by the algorithm.
30 MIN_COST = 4
31 # Maximum possible size of bcrypt() salts.
32 MAX_SALT_LENGTH = 16
33
34 if RUBY_PLATFORM != "java"
35 # C-level routines which, if they don't get the right input, will crash the
36 # hell out of the Ruby process.
37 private_class_method :__bc_salt
38 private_class_method :__bc_crypt
39 end
40
41 # Given a secret and a valid salt (see BCrypt::Engine.generate_salt) calculates
42 # a bcrypt() password hash.
43 def self.hash_secret(secret, salt, cost = nil)
44 if valid_secret?(secret)
45 if valid_salt?(salt)
46 if cost.nil?
47 cost = autodetect_cost(salt)
48 end
49
50 if RUBY_PLATFORM == "java"
51 Java.bcrypt_jruby.BCrypt.hashpw(secret.to_s, salt.to_s)
52 else
53 __bc_crypt(secret.to_s, salt, cost)
54 end
55 else
56 raise Errors::InvalidSalt.new("invalid salt")
57 end
58 else
59 raise Errors::InvalidSecret.new("invalid secret")
60 end
61 end
62
63 # Generates a random salt with a given computational cost.
64 def self.generate_salt(cost = DEFAULT_COST)
65 cost = cost.to_i
66 if cost > 0
67 if cost < MIN_COST
68 cost = MIN_COST
69 end
70 if RUBY_PLATFORM == "java"
71 Java.bcrypt_jruby.BCrypt.gensalt(cost)
72 else
73 __bc_salt(cost, OpenSSL::Random.random_bytes(MAX_SALT_LENGTH))
74 end
75 else
76 raise Errors::InvalidCost.new("cost must be numeric and > 0")
77 end
78 end
79
80 # Returns true if +salt+ is a valid bcrypt() salt, false if not.
81 def self.valid_salt?(salt)
82 salt =~ /^\$[0-9a-z]{2,}\$[0-9]{2,}\$[A-Za-z0-9\.\/]{22,}$/
83 end
84
85 # Returns true if +secret+ is a valid bcrypt() secret, false if not.
86 def self.valid_secret?(secret)
87 secret.respond_to?(:to_s)
88 end
89
90 # Returns the cost factor which will result in computation times less than +upper_time_limit_in_ms+.
91 #
92 # Example:
93 #
94 # BCrypt.calibrate(200) #=> 10
95 # BCrypt.calibrate(1000) #=> 12
96 #
97 # # should take less than 200ms
98 # BCrypt::Password.create("woo", :cost => 10)
99 #
100 # # should take less than 1000ms
101 # BCrypt::Password.create("woo", :cost => 12)
102 def self.calibrate(upper_time_limit_in_ms)
103 40.times do |i|
104 start_time = Time.now
105 Password.create("testing testing", :cost => i+1)
106 end_time = Time.now - start_time
107 return i if end_time * 1_000 > upper_time_limit_in_ms
108 end
109 end
110
111 # Autodetects the cost from the salt string.
112 def self.autodetect_cost(salt)
113 salt[4..5].to_i
114 end
115 end
116
117 # A password management class which allows you to safely store users' passwords and compare them.
118 #
119 # Example usage:
120 #
121 # include BCrypt
122 #
123 # # hash a user's password
124 # @password = Password.create("my grand secret")
125 # @password #=> "$2a$10$GtKs1Kbsig8ULHZzO1h2TetZfhO4Fmlxphp8bVKnUlZCBYYClPohG"
126 #
127 # # store it safely
128 # @user.update_attribute(:password, @password)
129 #
130 # # read it back
131 # @user.reload!
132 # @db_password = Password.new(@user.password)
133 #
134 # # compare it after retrieval
135 # @db_password == "my grand secret" #=> true
136 # @db_password == "a paltry guess" #=> false
137 #
138 class Password < String
139 # The hash portion of the stored password hash.
140 attr_reader :checksum
141 # The salt of the store password hash (including version and cost).
142 attr_reader :salt
143 # The version of the bcrypt() algorithm used to create the hash.
144 attr_reader :version
145 # The cost factor used to create the hash.
146 attr_reader :cost
147
148 class << self
149 # Hashes a secret, returning a BCrypt::Password instance. Takes an optional <tt>:cost</tt> option, which is a
150 # logarithmic variable which determines how computational expensive the hash is to calculate (a <tt>:cost</tt> of
151 # 4 is twice as much work as a <tt>:cost</tt> of 3). The higher the <tt>:cost</tt> the harder it becomes for
152 # attackers to try to guess passwords (even if a copy of your database is stolen), but the slower it is to check
153 # users' passwords.
154 #
155 # Example:
156 #
157 # @password = BCrypt::Password.create("my secret", :cost => 13)
158 def create(secret, options = { :cost => BCrypt::Engine::DEFAULT_COST })
159 Password.new(BCrypt::Engine.hash_secret(secret, BCrypt::Engine.generate_salt(options[:cost]), options[:cost]))
160 end
161 end
162
163 # Initializes a BCrypt::Password instance with the data from a stored hash.
164 def initialize(raw_hash)
165 if valid_hash?(raw_hash)
166 self.replace(raw_hash)
167 @version, @cost, @salt, @checksum = split_hash(self)
168 else
169 raise Errors::InvalidHash.new("invalid hash")
170 end
171 end
172
173 # Compares a potential secret against the hash. Returns true if the secret is the original secret, false otherwise.
174 def ==(secret)
175 super(BCrypt::Engine.hash_secret(secret, @salt))
176 end
177 alias_method :is_password?, :==
178
179 private
180 # Returns true if +h+ is a valid hash.
181 def valid_hash?(h)
182 h =~ /^\$[0-9a-z]{2}\$[0-9]{2}\$[A-Za-z0-9\.\/]{53}$/
183 end
184
185 # call-seq:
186 # split_hash(raw_hash) -> version, cost, salt, hash
187 #
188 # Splits +h+ into version, cost, salt, and hash and returns them in that order.
189 def split_hash(h)
190 _, v, c, mash = h.split('$')
191 return v, c.to_i, h[0, 29].to_str, mash[-31, 31].to_str
192 end
193 end
194end
195

Built with git-ssb-web