From 3916033058d350586625d6d8f830daf80f4cd9ff Mon Sep 17 00:00:00 2001 From: Julio Capote Date: Thu, 7 Jan 2010 16:08:01 +0800 Subject: [PATCH] added bcrypt as one of the encryptors --- lib/devise.rb | 3 ++- lib/devise/encryptors/bcrypt.rb | 24 ++++++++++++++++++++++++ test/encryptors_test.rb | 8 ++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 lib/devise/encryptors/bcrypt.rb diff --git a/lib/devise.rb b/lib/devise.rb index 338bfca5..a2ce0461 100644 --- a/lib/devise.rb +++ b/lib/devise.rb @@ -16,6 +16,7 @@ module Devise autoload :RestfulAuthenticationSha1, 'devise/encryptors/restful_authentication_sha1' autoload :Sha512, 'devise/encryptors/sha512' autoload :Sha1, 'devise/encryptors/sha1' + autoload :BCrypt, 'devise/encryptors/bcrypt' end module Orm @@ -179,4 +180,4 @@ end Warden::Strategies.clear! Warden::Serializers.clear! -require 'devise/rails' \ No newline at end of file +require 'devise/rails' diff --git a/lib/devise/encryptors/bcrypt.rb b/lib/devise/encryptors/bcrypt.rb new file mode 100644 index 00000000..16525e0c --- /dev/null +++ b/lib/devise/encryptors/bcrypt.rb @@ -0,0 +1,24 @@ +require "bcrypt" + +module Devise + # Implements a way of adding different encryptions. + # The class should implement a self.digest method that taks the following params: + # - password + # - stretches: the number of times the encryption will be applied + # - salt: the password salt as defined by devise + # - pepper: Devise config option + # + module Encryptors + # = BCrypt + # Uses the BCrypt hash algorithm to encrypt passwords. + class BCrypt + + # Gererates a default password digest based on stretches, salt, pepper and the + # incoming password. We don't strech it ourselves since BCrypt does so internally. + def self.digest(password, stretches, salt, pepper) + ::BCrypt::Engine.hash_secret(password, [salt, pepper].flatten.join('xx'), stretches) + end + + end + end +end diff --git a/test/encryptors_test.rb b/test/encryptors_test.rb index 212b981d..52cb4a24 100644 --- a/test/encryptors_test.rb +++ b/test/encryptors_test.rb @@ -17,6 +17,14 @@ class Encryptors < ActiveSupport::TestCase encryptor = Devise::Encryptors::ClearanceSha1.digest('123mudar', nil, '65c58472c207c829f28c68619d3e3aefed18ab3f', nil) assert_equal clearance, encryptor end + + test 'should match a password created by bcrypt' do + bcrypt = "$2a$10$81UWRL4S01M6zxjMPyBame1He8EHYgdFm26rQh0qKzglf2ijtEyfa" + encryptor = Devise::Encryptors::BCrypt.digest('123mudar', 4, '$2a$10$81UWRL4S01M6zxjMPyBame', '') + assert_equal bcrypt, encryptor + end + + Devise::ENCRYPTORS_LENGTH.each do |key, value| test "should have length #{value} for #{key.inspect}" do