Switch from SHA2 to BCrypt (easy Windows compatibility is coming shortly with new compiled gem)

This commit is contained in:
David Heinemeier Hansson 2010-12-18 15:39:32 -08:00
parent bcf4e4f2b0
commit 39b5ea6e01
4 changed files with 11 additions and 9 deletions

@ -1,6 +1,6 @@
*Rails 3.1.0 (unreleased)*
* Added ActiveModel::SecurePassword to encapsulate dead-simple password usage with SHA2 encryption and salting [DHH]
* Added ActiveModel::SecurePassword to encapsulate dead-simple password usage with BCrypt encryption and salting [DHH]
*Rails 3.0.2 (unreleased)*

@ -22,4 +22,6 @@
s.add_dependency('activesupport', version)
s.add_dependency('builder', '~> 3.0.0')
s.add_dependency('i18n', '~> 0.5.0')
s.add_dependency('bcrypt-ruby', '~> 2.1.2')
end

@ -1,4 +1,4 @@
require 'digest/sha2'
require 'bcrypt'
module ActiveModel
module SecurePassword
@ -44,13 +44,17 @@ def has_secure_password
module InstanceMethods
# Returns self if the password is correct, otherwise false.
def authenticate(unencrypted_password)
password_digest == encrypt_password(unencrypted_password) ? self : false
if BCrypt::Password.new(password_digest) == (unencrypted_password + salt_for_password)
self
else
false
end
end
# Encrypts the password into the password_digest attribute.
def password=(unencrypted_password)
@password = unencrypted_password
self.password_digest = encrypt_password(unencrypted_password)
self.password_digest = BCrypt::Password.create(unencrypted_password + salt_for_password)
end
private
@ -58,10 +62,6 @@ def salt_for_password
self.password_salt ||= self.object_id.to_s + rand.to_s
end
def encrypt_password(unencrypted_password)
Digest::SHA2.hexdigest(unencrypted_password + salt_for_password)
end
def password_must_be_strong
if @password.present?
errors.add(:password, "must be longer than 6 characters") unless @password.size > 6

@ -1,6 +1,6 @@
*Rails 3.1.0 (unreleased)*
* Added ActiveRecord::Base#has_secure_password (via ActiveModel::SecurePassword) to encapsulate dead-simple password usage with SHA2 encryption and salting [DHH]. Example:
* Added ActiveRecord::Base#has_secure_password (via ActiveModel::SecurePassword) to encapsulate dead-simple password usage with BCrypt encryption and salting [DHH]. Example:
# Schema: User(name:string, password_digest:string, password_salt:string)
class User < ActiveRecord::Base