Sha256: 23b1e36efb4f5cb7bfd669333fe1f3afc91066d79ce0d72db674138c1fb4e29e

Contents?: true

Size: 1.37 KB

Versions: 15

Compression:

Stored size: 1.37 KB

Contents

require 'digest/sha2'
require 'bcrypt'

module Challah  
  # Handles all encryption, hashing and comparison necessary for tokens and passwords.
  class Encrypter
    attr_accessor :cost, :joiner
    
    # The number of times to hash the given password.
    def cost
      @cost ||= 10
    end
    
    # Used to join multiple parameters for a given encrypt command.
    def joiner
      @joiner ||= "|"
    end
    
    # Passwords and secure objects are encrypted (hashed) in a one-way technique. This way
    # any item stored in the database can never be reversed into an actual password.
    def hash(*tokens)
      result = tokens.flatten.join(joiner)
      cost.times { result = Digest::SHA512.hexdigest(result) }
      result
    end
    
    def md5(*tokens)
      Digest::MD5.hexdigest(tokens.flatten.join(joiner))
    end
    
    def encrypt(secret)
      BCrypt::Password.create(secret, :cost => cost)
    end
    
    # Returns true if the the bcrypted value of a is equal to b
    def compare(crypted_string, plain_string)
      BCrypt::Password.new(crypted_string).is_password?(plain_string)
    rescue BCrypt::Errors::InvalidHash
      false
    end
    
    class << self
      # Setup some pass through convenience methods that use default options
      %w( hash md5 encrypt compare ).each do |f|
        class_eval %Q(def #{f}(*args); new.#{f}(*args); end )
      end
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
challah-0.5.4 lib/challah/encrypter.rb
challah-0.5.3 lib/challah/encrypter.rb
challah-0.5.2 lib/challah/encrypter.rb
challah-0.5.1 lib/challah/encrypter.rb
challah-0.5.0 lib/challah/encrypter.rb
challah-0.4.1 lib/challah/encrypter.rb
challah-0.4.0 lib/challah/encrypter.rb
challah-0.3.5 lib/challah/encrypter.rb
challah-0.3.4 lib/challah/encrypter.rb
challah-0.3.3 lib/challah/encrypter.rb
challah-0.3.2 lib/challah/encrypter.rb
challah-0.3.1 lib/challah/encrypter.rb
challah-0.3.0 lib/challah/encrypter.rb
challah-0.2.1 lib/challah/encrypter.rb
challah-0.2.0 lib/challah/encrypter.rb